C Programming Basics

In C, which of the following describes what happens when a null pointer is dereferenced (*p is read while p is NULL)?

  1. AThe standard requires it to be detected as a run-time error, so in every environment the program prints an error message and stops
  2. BNULL is defined to point to address 0, so in every environment the contents of address 0 are read and processing continues
  3. CIt is undefined behavior; under an OS it generally crashes, but on a microcontroller without an MMU address 0 may be readable and go unnoticed
Show answer and explanation

Answer: C. It is undefined behavior; under an OS it generally crashes, but on a microcontroller without an MMU address 0 may be readable and go unnoticed

Dereferencing a null pointer is undefined behavior, and the standard does not say what happens. Linux and Windows leave the pages around address 0 unmapped, so a dereference causes a page fault and the program generally terminates abnormally (a segmentation fault on Linux, for example). On a small microcontroller without an MMU, address 0 may hold flash memory or the interrupt vector table and be readable, so the error can cause malfunctions without ever surfacing. It is important to make sure a pointer is not NULL before using it.

  • A. The standard makes null pointer dereference undefined behavior and does not require it to be detected.
  • B. Null pointer dereference is undefined behavior. Under an OS, the area around address 0 is not mapped, and the program usually terminates abnormally.
  • C. Correct. Depending on the environment, it may crash or may keep running unnoticed.
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. Assume a typical environment where char is 1 byte and int is 4 bytes, with int placed at addresses that are multiples of 4. Which of the following is the output when the code above is executed?
  2. uint32_t and uint8_t are 32-bit and 8-bit unsigned integer types, and the environment is little-endian. Which of the following is the output when the code above is executed?
  3. Which of the following is the output when the code above, which stores 9 in a 3-bit bit-field, is executed?
  4. Which of the following is the output when the code above, which uses the macro SQUARE defined with #define, is executed?
  5. The header file sensor.h is written as above. Which of the following is the purpose of the three lines #ifndef, #define and #endif?