What is undefined behavior in C and C++? What about unspecified behavior and implementation-defined behavior? What is the difference between them?
C++ – Undefined, unspecified and implementation-defined behavior
c++implementation-defined-behaviorundefined-behaviorunspecified-behavior
Related Question
- C++ – the strict aliasing rule
- C++ – The Definitive C++ Book Guide and List
- C++ – the “–>” operator in C/C++
- C++ – Undefined behavior and sequence points
- Java – Why is processing a sorted array faster than processing an unsorted array
- C++ – an undefined reference/unresolved external symbol error and how to fix it
- C++ – Can code that is valid in both C and C++ produce different behavior when compiled in each language
Best Solution
Undefined behavior is one of those aspects of the C and C++ language that can be surprising to programmers coming from other languages (other languages try to hide it better). Basically, it is possible to write C++ programs that do not behave in a predictable way, even though many C++ compilers will not report any errors in the program!
Let's look at a classic example:
The variable
p
points to the string literal"hello!\n"
, and the two assignments below try to modify that string literal. What does this program do? According to section 2.14.5 paragraph 11 of the C++ standard, it invokes undefined behavior:I can hear people screaming "But wait, I can compile this no problem and get the output
yellow
" or "What do you mean undefined, string literals are stored in read-only memory, so the first assignment attempt results in a core dump". This is exactly the problem with undefined behavior. Basically, the standard allows anything to happen once you invoke undefined behavior (even nasal demons). If there is a "correct" behavior according to your mental model of the language, that model is simply wrong; The C++ standard has the only vote, period.Other examples of undefined behavior include accessing an array beyond its bounds, dereferencing the null pointer, accessing objects after their lifetime ended or writing allegedly clever expressions like
i++ + ++i
.Section 1.9 of the C++ standard also mentions undefined behavior's two less dangerous brothers, unspecified behavior and implementation-defined behavior:
Specifically, section 1.3.24 states:
What can you do to avoid running into undefined behavior? Basically, you have to read good C++ books by authors who know what they're talking about. Avoid internet tutorials. Avoid bullschildt.