I was under the impression that compiler optimisation often removed any NULL checks anyway [1].
1. http://blog.llvm.org/2011/05/what-every-c-programmer-should-...
I was under the impression that compiler optimisation often removed any NULL checks anyway [1].
1. http://blog.llvm.org/2011/05/what-every-c-programmer-should-...
Goodness.
No, you are misunderstanding the example. The optimizer did not introduce a bug by removing a NULL check. The code had a bug because it dereferenced the pointer before checking for NULL.
Are there any modern platforms where dereferncing a NULL pointer will not cause a crash?
Edit. Answering my own question it looks like ARM is one [1].
1. https://www.securecoding.cert.org/confluence/display/c/EXP34...
Incorrect. The example code did not check for a null pointer. It dereferenced a pointer, which implies that the pointer will never be null, and then it pointlessly checked for null on something that could not have been null. The optimizer in fact made the code more clear and easier to read, while maintaining correctness.
"While this is intentionally a simple and contrived example, this sort of thing happens all the time with inlining: inlining a function often exposes a number of secondary optimization opportunities. This means that if the optimizer decides to inline a function, a variety of local optimizations can kick in, which change the behavior of the code. This is both perfectly valid according to the standard, and important for performance in practice.”
In practice derefencing a NULL pointer on any x86 platform will always cause a crash (defined undefined behaviour I guess), but you can’t assume this on other platforms (ARM seems to be the big one).
I have to say before today I had assumed dereferncing a NULL pointer would always cause a segfault. It is always good to learn something new.