Discussion

Ask HN: Why can't C++ compilers find this error?

Debugging some 3rd party library I ran into a "reference a stack object that no longer exists" error. repo

    #include <iostream>
    int* f() { int x = 4; int* xp = &x; return xp; }
    
    int main() {
        int* p = f();
        std::cout << *p;
    }
Without giving it much thought, why is this hard for a modern C++ compiler to detect?

Note that gcc will detect some of these

    #include <iostream>
    
    int main() {
        int* p;
        { int j = 123; p = &j; }
        std::cout << *p;
    }
Gets an error in gcc (not in clang)

I know this type of issue is a strong reason people prefer rust but I'm still surprised a modern C++ compile doesn't find these issues. Is it an intractable issue?

1 points greggman7 1 year ago 3 comments

Discussion

Live from the official Hacker News API

A modern reader for Hacker News · SvelteKit + Skeleton