3 ms·
If the compiler can know that the pointer is non-null, why would it need to rely on UB to optimize it? You've got this backwards. The compilers "knows" the poi
by derf_ 9y ago
If the compiler can know that the pointer is non-null, why would it need to rely on UB to optimize it?
You've got this backwards. The compilers "knows" the pointer is non-null because you dereferenced it, and dereferencing null would have been undefined behavior. That's what allows the compiler to assume that didn't happen.
There are many operations which will produce undefined behavior for some inputs (e.g., every pointer dereference, every signed integer arithmetic operation). Figuring out if it is possible for a program to encounter such inputs at runtime is equivalent to the halting problem.
This is why any attempt to craft a -Wundefined-behavior that works on non-trivial programs is doomed to failure. It may be possible to prove a program will definitely invoke undefined behavior in some useful subset of cases. Compilers already do this in some of them, even. But those cases (and many more, besides) would also be caught with ubsan and a unit test.
- jononor 9y agoYou're right, it is an intractable problem in general. I guess just use Rust if one cares about this..