>>9does NOT get optimized out, because checking whether a pointer is NULL is NOT undefined behavior, and so the compiler cannot assume that the pointer is never null
You're right that it doesn't ``optimize out'' anything. It
removes code the programmer wrote.
Don't call that ``optimization''. It's offensive to non-C compiler writers because they care about the quality of the code. Non-C optimizers never do those things and can still be faster than C that does do those things.
http://blog.regehr.org/archives/213The idiom here is to get a pointer to a device struct, test it for null, and then use it. But there’s a problem! In this function, the pointer is dereferenced before the null check. This leads an optimizing compiler (for example, gcc at -O2 or higher) to perform the following case analysis:
As we can now easily see, neither case necessitates a null pointer check. The check is removed, potentially creating an exploitable security vulnerability.
This is the Linux kernel, which has control over memory mapping. C is supposed to be a systems language usable for writing kernels, but it isn't.
Why does the compiler even need to do this? What's the harm in leaving a check
the programmer wrote in the program if the compiler can't prove it's not necessary? It's because C is so incredibly hard to optimize.