What is 'Undefined Behavior' in C++, and why is it a significant concern?
Last updated
Undefined behavior (UB) is an operation the standard places no requirements on. Once executed, the whole program is invalid and anything may happen (unlike unspecified or implementation-defined behavior).
It is dangerous because optimizers assume UB never occurs and may delete checks or reorder code. Bugs can stay hidden until a release build, new compiler, or different input.
Common sources: out-of-bounds access, null/dangling pointers, signed overflow, data races, uninitialized reads. Catch them with sanitizers (
-fsanitize=address,undefined) and Valgrind.