C++ › Undefined Behavior

How can undefined behavior cause 'impossible' optimizations and bugs?

Advanced

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 check
Real-world example The optimizer removes a redundant-looking null check because an earlier dereference implied non-null, causing a crash on null input.

Common follow-ups: Why might a null check be removed? | Why does UB make bugs appear far from the cause?