Course contentsShow
← Computer Science
Lesson 2087 of 2,87247. Memory Management in LanguagesFree lesson

Memory Leaks: Causes and Detection

Understanding how failing to free allocated memory leads to leaks and techniques to identify them.

Memory Leaks: Causes and Detection

You'll learn: How memory leaks occur when you forget to free allocated memory, and practical techniques to find them before they crash your program.

What Is a Memory Leak?

A memory leak happens when your program allocates heap memory with malloc() but never calls free() to release it. Think of it like checking books out of a library but never returning them—eventually, the library runs out of books for other patrons.

When you allocate memory, the operating system reserves that space for your program. If you lose track of the pointer or exit a function without freeing the memory, those bytes remain claimed but unused. Over time, especially in long-running programs, these leaks accumulate and your program consumes more and more memory until the system runs out.

Common Causes

Lost pointers: Reassigning a pointer before freeing what it pointed to:

char *data = malloc(100);
data = malloc(200);  // Leak! Lost reference to first 100 bytes

Early returns: Exiting a function without freeing local allocations:

void process() {
    int *temp = malloc(50 * sizeof(int));
    if (error_condition) return;  // Leak if temp not freed
    free(temp);
}

Exception/error paths: Forgetting to free on all code paths through a function.

Detection Techniques

Manual code review: Trace each malloc() to ensure a matching free() on every execution path.

Valgrind: A powerful tool that tracks every allocation and reports leaks when your program exits.

Static analysis tools: Compilers and linters can detect some obvious leak patterns.

Runtime monitoring: Track memory usage over time—steadily increasing usage suggests leaks.

Key Takeaway: Memory leaks occur when allocated heap memory is never freed; detect them through careful code review, tools like Valgrind, and monitoring runtime memory consumption patterns.