Dangling Pointer
A dangling pointer holds the address of an object whose lifetime has ended. The bits still look like an address. Using them is undefined behavior.
Detailed Explanation
Three factories produce danglers.
Returning the address of a local. The frame is gone. The next call reuses the stack and overwrites the bytes. The pointer still "works" until then, which is why tests miss it.
free(p) without forgetting p. The heap block is dead. A later malloc may give those bytes to someone else. You then corrupt a different object.
A pointer into a realloced block after the block moved. The values were copied. The old address was not.
A pointer to a thread-local or to a mapping after munmap is the same idea. Lifetime ended; address remained.
The compiler does not track this. -Wreturn-local-addr catches the direct return &local. It does not catch *out = &local. AddressSanitizer catches many uses after free and some stack uses after return. It cannot make a dangling pointer safe.
Fixes are about ownership. The caller provides the buffer. The callee allocates and the contract says who frees. The object is static (and then you have a concurrency story). You copy out the value, not the address. You store an index into an array that still exists.
Setting p = NULL after free helps that one variable. Copies of p still dangle. A type system that encoded lifetime (Rust) would refuse the program. C expects you to write the lifetime in the comment and then obey it.
Code Examples
#include <stdio.h>
static int *bad(void)
{
int local = 7;
return &local; /* dangling the moment we return */
}
static void good(int *out)
{
int local = 7;
*out = local; /* copy the value */
}
int main(void)
{
int v = 0;
good(&v);
printf("%d\n", v); /* prints: 7 */
(void)bad;
return 0;
}#include <stdio.h>
#include <stdlib.h>
int main(void)
{
int *p = malloc(sizeof *p);
if (p == NULL) {
return 1;
}
*p = 1;
free(p);
p = NULL; /* this copy will not be reused by accident */
if (p != NULL) {
printf("%d\n", *p);
}
return 0;
}Common Gotchas
A dangling pointer that "still prints 7" is still undefined behavior
the next compiler upgrade or an extra `printf` can change the stack.
`NULL` is not dangling
it is a defined empty value. Dereferencing it is a different UB.
`realloc` invalidates pointers into the old block even if some of the values mov
`realloc` invalidates pointers into the old block even if some of the values moved