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

c
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

c
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

c
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

c
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 free as soon as you write the malloc, then fill in the middle.
  • Set the pointer to NULL immediately after freeing it.
  • Check the result of every malloc before using it.
  • Use < with the count, never <=.
  • Build with gcc -Wall -fsanitize=address while developing. It finds leaks and overruns and points at the line.

What does setting a pointer to NULL after free prevent?

Try this now

  1. Write a function that asks how many names to store, allocates room for them, reads them, prints them, and frees everything.
  2. Build it with gcc -Wall -fsanitize=address and check it reports no leaks.
  3. Remove the free on 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.