Re:Null Pointer Dereferencing Causes Undefined Behavior
by nkurz on Tuesday April 21, 2015 @04:41AM
(#9412850)
I like your detailed example, but wouldn't a slightly kinder but equally optimizing compiler simply add a conditional before the load:
if (max > 0) {
int i = max;
int tmp = p[0].foo;
do {
bar += tmp;
} while (--i);
}
I'd even argue the assembly is slightly better when interpreted this way, since branch prediction will tend execute the load or not as appropriate, rather than potentially taking a unnecessary TLB miss for a load that's never used.
So the compiler wants to prove that p is not NULL upon entry to the loop. And in this program, it can--because of the address computation, the behavior is undefined if p is NULL or one element beyond the end of an array. Therefore, the compiler can safely assume that p is not NULL and perform the loop invariant code motion. In this program, it can only do so thanks to the rule about undefined behavior in address computations.
Note that I'm not aware of any compiler that actually does this, because the C++ standard committee seems to consider this undefined behavior an oversight in the spec (per the discussion linked there). But the OP successfully argues that it could, per a lawyer-y reading of the spec.
Edit: Argh, I missed the case in which p was one element beyond the end of an array. Updated.