4 ms·
I don't think the compiler is supposed to treat an entire function behavior as undefined just because a pointer was dereferenced without checking for NULL. The
by phkahler 12y ago
I don't think the compiler is supposed to treat an entire function behavior as undefined just because a pointer was dereferenced without checking for NULL. The array indexing example may be valid, but the second one is probably not. It is possible to have a pointer to zero, and failing to check for that condition should not cause the compiler to assume the pointer is non-zero in subsequent lines of code.
- regehr 12y agoIt's not just the function that becomes undefined, it's the entire program. There's literally nothing that the compiler is supposed to do following undefined behavior.
- noselasd 12y agoIs the undefined behavior applicable at runtime or at compile time ? i.e. Is it undefined behavior if there are code paths that might access an array out of bounds, but at runtime it actually never would ?
- PeterisP 12y agoThat's the exact thing that the compiler is doing - if there are code paths that might access an array out of bounds, then the compiler is assuming that in runtime it actually never would happen. With this assumption you might even deduce that int f(int x) { if (x != 42) undefined_behavior; return x; } is the equivalent of int f(int x) { return 42; } since (according to the assumption) in runtime it would always be called in a way that doesn't reach the undefined behavior, i.e., with x=42. And, of course, the many similar assumptions about array boundaries, pointer nullabilities, numbers not reaching overflow, etc.
- PeterisP 12y agoIf you have a function that references a pointer without checking, then it's valid for the compiler to assume that it is not possible for that pointer to be null in subsequent lines of code, that's the whole point - if it sees that the pointer is used without checks, then this implies that all your other code somehow ensures that at that point it won't ever be null, that you've made sure that null pointers are checked somewhere else. The compiler often can't verify it (halting problem and friends), but it allows for nice optimizations by assuming that the code as written is actually correct, and the check was skipped intentionally.