Memory & Pointers

a dangling pointer and a wild pointer

A pointer is only as good as the address inside it, and two ways for that address to be bad have names. A dangling pointer once pointed at a valid object but the object is gone — it was freed, or it was a local whose function returned. A wild pointer never pointed anywhere meaningful — it is an uninitialised pointer holding whatever leftover bytes happened to be in its memory. Both look like ordinary pointers; both are landmines.

A dangling pointer is the more insidious because it used to be correct. After free(p), the block is returned to the allocator but p still holds the old address — the bytes there may even look unchanged for a while — so p is dangling until you reset it. Likewise, the address of a local variable dangles the instant its function returns and its stack frame is reused. A wild pointer is simply one you declared but never assigned: int *p; then *p = 5; writes through a garbage address. The common cure for both is discipline — initialise every pointer (to NULL if you have nothing yet), and after free(p) immediately do p = NULL so a stale use becomes a clean null-pointer crash instead of a use-after-free.

These are not theoretical: dereferencing or freeing either kind is undefined behaviour, and the failure is treacherous. Sometimes it is an immediate segmentation fault; sometimes it silently reads or corrupts whoever now owns those bytes, and the damage surfaces far away and much later. A dangling or wild pointer is a bug whether or not it has crashed yet — 'it seemed to work' is not evidence that it is safe.

free(p); ... *p = 1; uses p after free — p is dangling, this is use-after-free. The fix: free(p); p = NULL; so a later *p crashes cleanly. A wild pointer: int *q; *q = 1; writes through an uninitialised garbage address.

Set a pointer to NULL after free; never use an uninitialised pointer.

free() does not change the pointer or erase the bytes — the pointer is STILL dangling until you set it to NULL yourself. A dangling or wild pointer that has not crashed yet is not safe; the undefined behaviour may be corrupting memory silently and surfacing elsewhere.

Also called
stale pointeruninitialised pointer懸置指標野指標