What is Undefined behavior?
Behavior for which the C or C++ standard imposes no requirements. Examples are signed integer overflow, reading or writing outside an array, dereferencing a null pointer, using freed memory and left-shifting a negative value. A compiler may optimize on the assumption that a correct program never has undefined behavior, so such code may happen to work as expected, or may give unexpected results, for example a check disappearing under some optimization settings. It is distinguished from implementation-defined behavior, which the implementation chooses and documents.
Japanese name: 未定義動作
Undefined behavior appears in 11 practice questions across 3 topics, including C Programming Basics, Compilers, Multicore & Synchronization.
Field: C Programming Basics
FAQ
What is the difference between undefined behavior and implementation-defined behavior?
Implementation-defined behavior, such as the size of int, whether char is signed, or the result of right-shifting a negative value, is behavior for which the implementation chooses one option and documents it. Undefined behavior is behavior on which the standard imposes no requirements, and the result may differ from case to case even with the same implementation. Portable programs make any reliance on implementation-defined behavior explicit and avoid undefined behavior altogether.
If code with undefined behavior works, is it a problem?
Yes. Even if it happens to work as expected in the current environment, a change in optimization settings, the compiler version or the surrounding code can give a different result. From a security point of view as well, undefined behavior such as out-of-bounds writes can be exploited by attackers.