Pointers & Memory · intermediate · ~10 min

Memory leaks

Recognize and prevent leaks; use valgrind or asan to find them.

Lesson

A leak is allocated memory that nothing points to anymore — you can no longer free it. Long-running services with leaks eventually exhaust RAM and die.

Detect leaks with Valgrind's memcheck or AddressSanitizer (-fsanitize=address) — both report exactly which allocation never got freed and where it was allocated. Adopt the discipline early.

Common mistakes

  • Returning from a function on an error path before freeing locally-allocated memory.
  • Replacing a pointer (p = malloc(...)) without freeing what it used to point to.