Topics / C Programming / Q33
What is a dangling pointer, a wild pointer and a NULL pointer?
Short answer: A NULL pointer deliberately points to nothing; dereferencing it is undefined behaviour. A wild pointer is an uninitialised pointer containing a random address. A dangling pointer still holds the address of an object that no longer exists: memory that was freed, or a local variable whose function has returned.
int *wild; /* wild: indeterminate value */
*wild = 5; /* writes to a random address */
int *dang = malloc(sizeof *dang);
free(dang);
*dang = 5; /* dangling: use after free */
int *get_local(void)
{
int x = 42;
return &x; /* dangling: x is gone when the function returns */
}
int *np = NULL;
*np = 1; /* NULL dereference: undefined behaviour */
Why they are dangerous in embedded systems
- On a Cortex-M, address 0 is usually the start of flash (or the vector table). A NULL read returns the initial stack pointer value instead of faulting, and a NULL write may be silently ignored or cause a bus fault depending on the memory map. Bugs survive testing.
- A dangling pointer to a stack frame may "work" until an interrupt or another call overwrites that stack area.
Prevention
- Initialise every pointer, to a valid object or
NULL. - Set pointers to
NULLafterfree()(and avoid keeping several copies of an owning pointer). - Never return the address of a non-static local.
- Check pointers from callers and from allocation (
if (p == NULL)). - Use the MPU to make the first few hundred bytes at address 0 inaccessible so NULL dereferences fault immediately.
- Run code on the host with AddressSanitizer (
-fsanitize=address) and use static analysis to catch use-after-free and uninitialised use.
Interview follow-up: "Is free(NULL) safe?" Yes, it does nothing. "Is double free safe?" No, it is undefined behaviour and can corrupt the heap.