← The C Language Lesson 52 of 77 · 10 XP

Freeing memory: free

Theory and problem statement

Machine translation, not yet reviewed by a native speaker.

Every malloc, calloc and realloc must be matched by exactly one free:

int *a = malloc(100 * sizeof *a);
...
free(a);
a = NULL;          // a good habit: if you accidentally call free(a) again, it's free(NULL), which is safe

Three rules:

  1. Don't free twice (double free) — it corrupts the heap, and attackers know how to exploit that.
  2. Don't access memory after free (use-after-free) — the memory may already belong to something else.
  3. Free only what was allocated by malloc: calling free on an array on the stack or on the middle of a block is an error.

By the standard, free(NULL) does nothing, so there's no need to check before it.

When a program ends, the OS takes back all its memory. But in long-running programs (a server, a game) leaks pile up until the memory runs out.

Tools help you find leaks: valgrind ./main on Linux or the compiler flag -fsanitize=address.

Task. The function make_names allocates an array of strings, and each string is allocated on the heap too. Write free_names(char **names, int n), which frees everything: first each string, then the array itself. The program reads words, prints them separated by spaces and calls your function. Your function must return how many calls to free it made. This lets the test check that you didn't forget anything.

Sign up for free to solve this task right in your browser: code editor, running, test checks and hints.