C Programming Basics
Which of the following describes undefined behavior as defined by the C standard?
- ABehavior the standard places no requirements on; the compiler may optimize assuming it never happens, so results can be unexpected
- BBehavior for which each implementation decides the result and is required to document it
- CBehavior that is always detected at run time, printing an error message and stopping the program
Show answer and explanation
Answer: A. Behavior the standard places no requirements on; the compiler may optimize assuming it never happens, so results can be unexpected
Undefined behavior is behavior on which the standard imposes no requirements, such as signed integer overflow, out-of-bounds array access, null pointer dereference and use after free. It may happen to work as expected, but because the compiler may optimize on the assumption that it "does not happen in a correct program", merely changing optimization settings or the compiler version can change the result. In contrast, things such as the size of int and whether char is signed, which the implementation decides and must document, are called implementation-defined behavior. With gcc and clang, -fsanitize=undefined detects some undefined behavior at run time.
- A. Correct. The standard imposes no requirements, so no result violates the standard.
- B. This describes implementation-defined behavior. The size of int and the signedness of char are examples.
- C. The standard does not require detection. In many cases the result is simply wrong with no notice.