How can undefined behavior cause 'impossible' optimizations and bugs?
Short answer
Because compilers assume UB never happens, they may delete checks or code paths that would only matter if UB occurred—e.g., removing a null check after a dereference (which implied the pointer was non-null), or assuming a loop terminates.
Advertisement
AModel answer
Because compilers assume UB never happens, they may delete checks or code paths that would only matter if UB occurred—e.g., removing a null check after a dereference (which implied the pointer was non-null), or assuming a loop terminates. This can make bugs appear far from their cause and behave differently across optimization levels, making UB especially insidious.
int* p = get(); *p; if (p) use(p); // compiler may drop the null checkReal-world example
The optimizer removes a redundant-looking null check because an earlier dereference implied non-null, causing a crash on null input.
Likely follow-ups
- Why might a null check be removed? | Why does UB make bugs appear far from the cause?
Related topics