Lesson 103 +10 XP

Freeing Memory

Freeing Memory

Everything you allocate eventually returns via free.

The call

free(ptr);

It returns the block to the system so the program doesn't leak.

Memory leaks

Forgetting free causes memory leaks: the program slowly eats memory until it's gone.

for (int i = 0; i < 1000000; i++) {
    int *p = malloc(sizeof(int));
    // forgot free(p)  -> leak!
}

Use-after-free bug

Using a pointer after freeing it is undefined behavior:

free(ptr);
*ptr = 5;   // BAD: ptr is dangling

Double free

Freeing the same block twice is also a bug. Only free once per allocation.

TL;DR

  • Free every allocation when done.
  • Leaks happen when you don't.
  • Don't use after free (dangling pointer).
  • Don't free the same block twice.