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)?
- AThe standard requires it to be detected as a run-time error, so in every environment the program prints an error message and stops
- BNULL is defined to point to address 0, so in every environment the contents of address 0 are read and processing continues
- 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.