C Programming Basics

Which of the following describes undefined behavior as defined by the C standard?

  1. ABehavior the standard places no requirements on; the compiler may optimize assuming it never happens, so results can be unexpected
  2. BBehavior for which each implementation decides the result and is required to document it
  3. 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.
Practice this topic Back to topic

Books on C Programming Basics Ad

As an Amazon Associate I earn from qualifying purchases.

More C Programming Basics questions

  1. int and unsigned int are 32 bits. Which of the following is undefined behavior according to the C standard?
  2. When the function above is compiled with gcc with optimization enabled, the check if (p == NULL) may be removed. Which of the following is the reason?
  3. Which of the following is what the C standard specifies about the size of the int type?
  4. In embedded programs, variables that hold the value of a 32-bit peripheral register are often declared with uint32_t from stdint.h rather than unsigned int. Which of the following is the main reason?
  5. Which of the following is the output when the code above, which includes a division of integers, is executed?