Course contentsShow
← Computer Science
Lesson 323 of 2,8728. Linked Data StructuresFree lesson

Memory Leaks and Manual Deallocation

Recognizing memory leaks from missing free/delete calls and the importance of proper memory cleanup.

Memory Leaks and Manual Deallocation

You'll learn: Why forgetting to free dynamically allocated memory causes leaks and how to prevent them.

The Problem: Forgetting to Clean Up

When you dynamically allocate memory (using malloc in C or new in C++), the program reserves space on the heap. Unlike stack variables that automatically disappear when their scope ends, heap memory stays allocated until you explicitly deallocate it.

A memory leak occurs when you lose all references to dynamically allocated memory without freeing it first. That memory becomes inaccessible but still occupied—like losing the key to a storage unit you're still paying for.

Why This Matters

Memory is finite. Each leak consumes system resources that can never be reclaimed while your program runs. In long-running applications, repeated leaks can exhaust available memory, causing crashes or severe performance degradation.

Preventing Leaks

The golden rule: Every allocation needs a corresponding deallocation.

  • In C: Every malloc needs a free
  • In C++: Every new needs a delete (or delete[] for arrays)

Common leak scenarios:

  • Overwriting a pointer before freeing: If you reassign a pointer to new memory without freeing the old memory first, the original allocation is lost forever
  • Early function returns: Forgetting to free before returning from a function
  • Exception/error paths: Not freeing memory when error handling causes early exits

Think of dynamic memory like borrowing books from a library. You must return each book (deallocation) when finished, or you'll accumulate late fees and eventually be blocked from borrowing more.

Key Takeaway: Always pair each dynamic allocation with exactly one deallocation to prevent memory leaks—memory you allocate is your responsibility to clean up.