Lesson 29 / 36

Memory Leaks & Dangling Pointers

What goes wrong when heap memory isn't managed carefully.

A leak: memory you can never reach again

If you overwrite or lose the only pointer to a malloc'd block without freeing it first, that memory stays reserved forever — a memory leak. Long-running programs (servers, games) leaking repeatedly will eventually run out of memory.

A dangling pointer

After free, the pointer still holds the old address — using it is undefined behavior, even though the compiler won't stop you.

int *p = malloc(sizeof(int));
*p = 42;
free(p);

printf("%d\n", *p); // BUG: use-after-free
p = NULL;             // now safe: NULL is checkable

Rule of thumb

Every malloc/calloc should have exactly one matching free. Set the pointer to NULL right after freeing so an accidental reuse fails loudly instead of silently corrupting memory.

Quick check: What should you do to a pointer immediately after calling free() on it?

  • Set it to NULL
  • Call free() on it again
  • Nothing, it's fine to keep using it
Answer

Set it to NULL — Setting it to NULL prevents accidental use-after-free bugs.