Memory Leaks in C: How malloc and free Work and How to Find Leaks
Every time you call malloc you borrow memory from the heap, and free gives it back. If you forget to give it back, that memory stays reserved until your program ends. That is a memory leak. One small leak is harmless, but a program that runs for hours can slowly use up all available memory.
malloc and free in one example
#include <stdlib.h>
int main(void)
{
int *arr = malloc(5 * sizeof(int));
if (arr == NULL)
{
return (1);
}
arr[0] = 42;
free(arr);
return (0);
}
The rule is simple: every successful malloc needs exactly one free.
What a leak looks like
void leaky(void)
{
int *arr = malloc(100 * sizeof(int));
arr[0] = 1;
}
When leaky returns, the pointer variable arr disappears, but the 400 bytes it pointed to (assuming 4-byte ints) are still reserved and now nobody knows where they are. Call this function in a loop and the leak grows with every call.
Hidden leak 1: early returns
int process(void)
{
char *buf = malloc(256);
if (buf == NULL)
{
return (-1);
}
if (check_failed())
{
return (-1); /* leak: buf was never freed */
}
free(buf);
return (0);
}
Every path out of the function must free what the function allocated. Add free(buf); before the second return.
Hidden leak 2: overwriting the only pointer
p = malloc(10);
p = malloc(20); /* the first block is now lost */
Once the only pointer to a block is overwritten, you can never free that block.
Hidden leak 3: realloc
p = realloc(p, new_size);
If realloc fails it returns NULL but leaves the original block valid. Assigning the result straight to p throws away your only pointer to it. Use a temporary variable:
int *tmp = realloc(p, new_size);
if (tmp == NULL)
{
free(p);
return (1);
}
p = tmp;
Finding leaks with Valgrind
gcc -g -o app app.c
valgrind --leak-check=full ./app
Valgrind reports lines such as "400 bytes in 1 blocks are definitely lost" together with the line of the malloc call that created them. On Linux you can also compile with -fsanitize=address, which includes a leak detector.
Habits that prevent leaks
- When you write
malloc, decide right away where the matchingfreewill be - Keep ownership clear: the function or module that allocates is responsible for freeing
- Set the pointer to NULL after freeing it, because
free(NULL)is safe - Re-read every
returnin a function that allocates memory - Run Valgrind on your finished programs, not just the broken ones
Freed memory brings its own danger when a pointer is still used afterwards, which is the topic of our guide to dangling pointers. For a full walkthrough of dynamic memory with diagrams, see the Data Structures notes on automatic and dynamic allocation.