Memory leaks, dangling pointers and double frees
The classic C memory bugs, what causes them, and how to find them with AddressSanitizer and Valgrind.
- Leak: heap memory is never freed, usually because the last pointer to it was overwritten or a function returned early.
- Dangling pointer: using memory after
free. The pointer still holds the old address, but the memory is no longer yours. - Double free: calling
freetwice on the same block. Setting the pointer toNULLafter freeing makes a secondfreeharmless. - Buffer overflow: writing past the end of a block.
None of these reliably crash, which is what makes them dangerous. Compile with -fsanitize=address -g while developing and the program stops at the exact line, or run it under valgrind.
Example
#include <stdio.h>
#include <stdlib.h>
int main(void) {
char *buf = malloc(8);
if (!buf) return 1;
buf[0] = 'o';
buf[1] = 'k';
buf[2] = '\0';
printf("%s\n", buf);
free(buf);
buf = NULL;
free(buf);
return 0;
}
Output:
ok
Watch it run: Returning heap memory from a function