Dangling Pointers in C: Use After Free and Returning Local Addresses
A dangling pointer is a pointer that still holds an address, but the memory at that address is no longer yours to use. Reading or writing through it is undefined behavior, which means anything can happen: a crash, garbage values or, worst of all, a program that seems to work until the day it does not.
Cause 1: using memory after free
int *p = malloc(sizeof(int));
*p = 7;
free(p);
printf("%d\n", *p); /* undefined behavior */
After free, the memory goes back to the system. It may still contain 7, it may contain something else or it may be unmapped and crash your program. Because it sometimes appears to work, this bug is hard to spot.
The fix is a one-line habit:
free(p);
p = NULL;
Now a mistaken use of p crashes immediately at a clear place instead of silently corrupting data. A loud failure is much easier to debug.
Cause 2: returning the address of a local variable
int *make_number(void)
{
int n = 5;
return (&n); /* n is destroyed when the function ends */
}
Local variables live only while their function runs. The compiler usually warns you with "function returns address of local variable". There are three common fixes:
- Allocate with
mallocand let the caller free the result - Let the caller provide the storage
- Return the value itself instead of an address
void make_number(int *out)
{
*out = 5;
}
Cause 3: freeing twice
free(p);
free(p); /* undefined behavior */
A double free can corrupt the memory manager's bookkeeping. If you set p = NULL after the first free, the second call becomes free(NULL), which does nothing.
Cause 4: a pointer into memory that moved
int *a = malloc(3 * sizeof(int));
int *first = &a[0];
a = realloc(a, 100 * sizeof(int));
/* first may now point to the old, freed block */
realloc is allowed to move your data to a new location. Any other pointer into the old block is now dangling, so recalculate such pointers after a realloc.
How to catch these bugs
- Compile with
-Wall -Wextrato get warnings about local addresses - Use
gcc -g -fsanitize=address, which reports "heap-use-after-free" with the exact line - Run
valgrind ./app, which reports "Invalid read" and "Invalid write" errors
Checklist
- Set pointers to NULL right after
free - Never return the address of a local variable
- Free each block exactly once
- Recalculate pointers after
realloc - Keep track of which part of your program owns each block
Leaks are the opposite problem, memory that is never freed. You can read about them in memory leaks in C, and if you need a refresher on the basics start with what a pointer is.