What is a NULL pointer dereference on a Cortex-M and why might it not crash?
Short answer: On most Cortex-M microcontrollers, address 0x00000000 is valid memory: flash (or an alias of it) containing the vector table. Reading through a NULL pointer therefore returns real data (the initial stack pointer value and the reset vector) instead of faulting, so the bug goes unnoticed. Writes to that area are usually ignored or cause a bus fault, depending on the part.
Example
struct sensor *s = NULL; /* forgot to initialise */
uint32_t v = s->value; /* reads address 0x00000000 + offset: valid flash, no fault */
s->value = 5; /* write to flash: ignored, or a BusFault (imprecise on some cores) */
On Linux, the first page (and more) of every process is unmapped, so the same bug gives an immediate SIGSEGV.
How to catch NULL dereferences on an MCU
- MPU: configure a region at address 0 (e.g. 256 bytes to a few KB) as no-access. If the vector table has been relocated to RAM or another flash address with
SCB->VTOR, nothing legitimate reads address 0 any more, and the MPU turns a NULL access into a MemManage fault with the faulting address inMMFAR. - Some MCUs let you remap address 0 to non-existent memory, or have the flash at another base address with nothing at 0 (then a NULL access is a precise BusFault).
- Static analysis and compiler warnings (
-Wnull-dereference, clang analyzer, cppcheck). - Unit-test the code on the host with sanitizers, where NULL dereferences crash reliably.
- Defensive coding: check pointers returned by allocation and lookup functions; initialise every pointer.
Why it matters: a NULL function pointer call (cb() where cb == NULL) loads the PC from address 0 — the initial stack pointer value — and the core tries to execute at an address in RAM, usually ending in a HardFault far from the cause. Knowing this pattern helps you recognise it in a fault dump: a PC equal to the initial MSP value is a strong hint.