Skip to content
Tutorials Center
My learning

Topics

Lesson 61 of 171 ยท Pointers, References and Memory

Memory Leaks: Causes, Detection and Prevention

Learn how memory leaks happen in C++ - early returns, exceptions, lost pointers, owning containers, constructors that throw - and how RAII, smart pointers and LeakSanitizer fix them.

A memory leak is memory your program no longer uses but never gave back. The allocation is still there, the allocator still counts it as yours, and nothing in the program can free it because the last pointer to it is gone. A single leaked object does no harm. A leak inside a request handler, a game loop or a background service adds up, until the process is slow, swapped out or killed by the operating system.

The Dynamic Memory lesson introduced leaks as one of four classic new/delete bugs. This lesson goes deeper, because leaks come in more shapes than "forgot to call delete". You will learn the common patterns, how to tell a leak from a dangling pointer, how to measure leaks yourself, how to prevent them with RAII and smart pointers, and how to find the ones that slip through using LeakSanitizer and Valgrind.

Leaked, dangling and still reachable

Three words get mixed up, so let's separate them.

  • Leaked memory is allocated, unreachable and never freed. No pointer holds its address any more.
  • A dangling pointer is the opposite problem: the memory was freed, but a pointer still holds the old address. Using it is undefined behavior (see Undefined Behavior and Memory Safety).
  • Still reachable memory is allocated and some pointer (often a global) still points to it when the program exits. Tools report it, but it is usually harmless because the operating system reclaims everything at exit.

A leak is a lost owner problem. The fix is never "delete more carefully"; it is to make sure every allocation always has exactly one owner whose destructor frees it. Everything below is a variation on that idea.

Counting live objects

To see leaks without any special tool, give a class a counter that goes up in the constructor and down in the destructor. If the count is not back to its starting value when you expect it to be, something leaked. The Blob type below does that, and each function leaks in a different way.

C++ Four ways to leak a Blob

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with std::cin or std::getline), it gets the next line from this box.

The first call is fine: the count stays at 0. After that every call leaves something behind, and the count climbs: one for the early return, one for the exception, one for the overwritten pointer, and three for the vector of raw pointers. No crash, no error message, no wrong output. That silence is why leaks survive code review and testing and only show up in production.

All four share one shape: ownership is expressed by a raw pointer plus a promise to call delete on every path. A promise like that breaks as soon as the code changes, or an exception flies through, or a pointer is reassigned.

The fix: give every allocation an owner

Replace "a pointer and a promise" with an object whose destructor does the freeing. C++ guarantees destructors of local objects run on every exit from a scope, including return and exceptions. This is RAII. For heap objects, the owner is std::unique_ptr (see unique_ptr) or a container that stores the objects directly.

C++ The same four functions, leak-free

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with std::cin or std::getline), it gets the next line from this box.

Every path now ends at zero. Notice what changed and what didn't: the logic is identical, but there is no delete anywhere. If a Blob does not need to live on the heap at all, an even simpler fix is std::vector<Blob> or a plain local variable. Reach for unique_ptr when you need polymorphism, stable addresses or a size not known at compile time.

A quick audit rule: when you read a new in application code, ask who owns the result. If the answer is "a unique_ptr created on the same line", fine. If the answer is "a raw pointer and some later delete", you have found a future leak.

Leaks hidden in constructors

One leak is easy to miss because it looks safe. If a constructor throws, the object was never fully constructed, so its destructor never runs. Members that were already built are destroyed, but a raw pointer member is just a number, and destroying a number frees nothing.

C++ A constructor that throws halfway

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with std::cin or std::getline), it gets the next line from this box.

RawHolder leaks the first Part, because the exception stopped the constructor before it finished and ~RawHolder was skipped. SafeHolder leaks nothing: the first unique_ptr member was fully constructed, so the language destroys it during unwinding. The lesson is general. Never let a class own two raw resources; give each its own owning member and the compiler-generated destructor, and the constructor's failure behavior will be correct automatically (see Rule of Zero, Three and Five).

Other leak patterns to know

  • Reference cycles. Two shared_ptr objects that own each other never reach a count of zero. Break the cycle with a weak_ptr on the back link. The mechanics are in shared_ptr and weak_ptr.
  • release() ignored. unique_ptr::release() gives up ownership without freeing. Calling it and discarding the result is a leak; use reset() to delete.
  • new[] freed with the wrong form. delete p on an array is undefined behavior, not just a leak. Prefer std::vector or std::make_unique<T[]>(n).
  • Missing virtual destructor. Deleting a derived object through a base pointer without a virtual destructor is undefined behavior, and in practice the derived members are never cleaned up. Make base-class destructors virtual (see Virtual Functions).
  • C resources. fopen without fclose, malloc without free, and OS handles leak just like new does. Wrap them in a small RAII class or a unique_ptr with a custom deleter.
  • std::exit and abrupt termination. Calling std::exit does not unwind the stack, so local objects are not destroyed. Return from main normally when you want cleanup to run.

Logical leaks: memory that is still reachable

Smart pointers cannot protect you from the second kind of leak: memory that is still owned, but should have been released long ago. A cache that only ever grows, a log that is never trimmed, a list of listeners that nobody unsubscribes. Every allocation has a perfectly good owner, so no leak detector complains, yet memory use rises forever.

C++ An unbounded cache and a bounded one

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with std::cin or std::getline), it gets the next line from this box.

After 50,000 distinct requests the first cache holds all 50,000 entries while the second never exceeds 1,000. A real production cache would use least-recently-used eviction and expiry times, but the principle is the same: every container that grows with input needs a plan for shrinking. When you suspect a logical leak, compare the size of long-lived containers over time; a heap profiler (Valgrind's Massif, or heaptrack) shows which allocation sites keep growing.

Finding leaks with tools

Counters are great for tests you write yourself. For programs you did not instrument, use a leak detector. These examples are commands, shown read-only because the in-browser runner does not pass sanitizer flags.

LeakSanitizer ships with GCC and Clang on Linux and is part of AddressSanitizer. Compile with debug info and run the program normally; at exit it prints every unreachable allocation with the stack trace that created it.

Terminal
g++ -std=c++23 -g -fsanitize=address -fno-omit-frame-pointer leaky.cpp -o leaky
./leaky

A shortened report looks like this:

TEXT
==4242==ERROR: LeakSanitizer: detected memory leaks

Direct leak of 4 byte(s) in 1 object(s) allocated from:
    #0 0x7f... in operator new(unsigned long)
    #1 0x401... in early_return(bool) leaky.cpp:12
    #2 0x401... in main leaky.cpp:30

SUMMARY: AddressSanitizer: 4 byte(s) leaked in 1 allocation(s).

Read it bottom-up from the frame in your own code: early_return, line 12 is the new whose pointer was lost. A direct leak is memory nothing points to; an indirect leak is memory only reachable through a direct leak (for example the nodes behind a leaked list head), so fixing the direct leak fixes both.

Valgrind needs no recompilation, only -g for line numbers, and is slower but widely available:

Terminal
valgrind --leak-check=full --show-leak-kinds=all ./leaky

Focus on the definitely lost and indirectly lost lines first. Still reachable entries are usually global state released only at exit. The Sanitizers and Valgrind lesson covers both tools in more detail, and Static Analysis shows how clang-tidy and the compiler's analyzer catch simple leaks before the program even runs.

Prevention checklist

  1. No raw owning pointers. Raw pointers and references may observe; they must never be the only thing responsible for a delete.
  2. Prefer values. Use locals, members and std::vector before heap allocation.
  3. make_unique by default. Move to shared_ptr only when ownership really is shared, and use weak_ptr for back references.
  4. One resource per owner. A class that holds a single resource-managing member needs no destructor at all.
  5. Bound your containers. Caches, queues, histories and listener lists need a limit or an eviction rule.
  6. Test with a sanitizer. Run the unit tests under ASan/LSan in continuous integration so a new leak fails the build the day it is introduced.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. A function does Blob* p = new Blob; and then throws before reaching delete p;. What happens to the Blob?

    Stack unwinding destroys local objects, but destroying a raw pointer variable does nothing to the object it points to. Wrapping the pointer in unique_ptr fixes this.
  2. 2. What is the difference between a leaked object and a dangling pointer?

    A leak loses the owner so the memory is never released. A dangling pointer is the reverse: the memory is released but a pointer still refers to it, and using it is undefined behavior.
  3. 3. A constructor allocates two raw pointer members with new, and the second allocation's constructor throws. Why does the first allocation leak?

    The object never finished construction, so its destructor is skipped. Members that were fully built are destroyed, but a raw pointer has no destructor effect. Using unique_ptr members makes the first one clean itself up.
  4. 4. A cache stores every result in a std::unordered_map and never removes entries. Which statement is true?

    Every entry has an owner, so leak detectors stay quiet, yet memory use keeps growing. The fix is a design change such as a capacity limit or eviction policy.
  5. 5. Which tool reports leaked allocations together with the stack trace of the new that created them, without recompiling?

    Valgrind runs the finished binary and reports lost blocks with allocation stacks (build with -g for line numbers). LeakSanitizer gives similar reports but requires compiling with -fsanitize=address.

Summary

  • A leak is memory with no remaining owner that is never freed; it is silent, so you must look for it.
  • Typical causes are early returns, exceptions, overwritten pointers, containers of raw owning pointers, constructors that throw halfway, release() without a delete, and shared_ptr cycles.
  • The cure is RAII: every allocation gets an owner whose destructor frees it on every path. Prefer values and containers, then make_unique, then shared_ptr/weak_ptr.
  • Logical leaks (unbounded caches, logs and listener lists) keep memory reachable, so tools stay quiet; bound every container that grows with input.
  • Detect leaks with a live-object counter in tests, LeakSanitizer (-fsanitize=address), or Valgrind (--leak-check=full), and run one of them in CI.

Next: Memory Layout, where you'll see how the stack, heap and static storage are arranged in a running program.