Lesson 2 of 2 · Dynamic Memory · 3 min read · Updated
The four memory mistakes
Leaks, double frees, use-after-free, and off-by-one — what they look like and how to avoid them.
Nearly every memory bug in C is one of four mistakes. None of them is hard to understand; all of them are easy to make when you are busy.
1. The leak
void leaky(void)
{
int *p = malloc(100 * sizeof(int));
p[0] = 42;
/* no free — the memory is never given back */
}
Call that in a loop and the program grows until the machine runs out. A leak in a program that exits quickly is harmless; a leak in something that runs for weeks is how servers fall over at 3am.
2. Use after free
int *p = malloc(sizeof(int));
*p = 5;
free(p);
printf("%d\n", *p); /* the memory is not yours any more */
/* The fix: make the pointer say so. */
free(p);
p = NULL; /* now using it crashes loudly */
Note
Setting a pointer to NULL after freeing it turns a silent, unpredictable bug into an immediate crash at the exact line that is wrong. A crash you can find beats corruption you cannot.
3. The double free
free(p);
free(p); /* corrupts the memory allocator itself */
/* Setting p = NULL after the first free prevents this too:
free(NULL) is defined to do nothing. */
4. Off by one
int *a = malloc(5 * sizeof(int));
for (int i = 0; i <= 5; i++) { /* <= writes 6 values into room for 5 */
a[i] = i;
}
for (int i = 0; i < 5; i++) { /* correct */
a[i] = i;
}
Habits that prevent all four
- Write the
freeas soon as you write themalloc, then fill in the middle. - Set the pointer to
NULLimmediately after freeing it. - Check the result of every
mallocbefore using it. - Use
<with the count, never<=. - Build with
gcc -Wall -fsanitize=addresswhile developing. It finds leaks and overruns and points at the line.
What does setting a pointer to NULL after free prevent?
Try this now
- Write a function that asks how many names to store, allocates room for them, reads them, prints them, and frees everything.
- Build it with
gcc -Wall -fsanitize=addressand check it reports no leaks. - Remove the
freeon purpose and run it again, so you know what a leak report looks like before you meet one by accident.
Create a free account to save your progress, or sign in.