What is undefined behavior (UB) in C++?
Short answer
Undefined behavior is program behavior the C++ standard places no requirements on—anything can happen: a crash, wrong results, or seemingly working code that breaks later or under optimization. The compiler may assume UB never occurs and optimize accordingly.
Advertisement
AModel answer
Undefined behavior is program behavior the C++ standard places no requirements on—anything can happen: a crash, wrong results, or seemingly working code that breaks later or under optimization. The compiler may assume UB never occurs and optimize accordingly. UB arises from invalid operations like out-of-bounds access, use-after-free, or signed overflow.
Example
int a[3]; a[5] = 1; // out-of-bounds: undefined behavior
Real-world example
Code that 'worked' in debug crashes in release because the optimizer exploited an assumption of no UB.
Likely follow-ups
- Can the compiler assume UB never happens? | Give an example of UB.
Related topics