The Analogy: Paying Rent on Units You Have Lost the Keys To
A memory leak is not memory that vanished. The storage unit is still there, still full, still on your bill — you have simply lost the only key, so you can neither use it nor give it back. The rental office will keep charging you until the day you go out of business.
That is the shape of the bug, and it explains why leaks are so easy to miss. Nothing crashes. Nothing prints an error. The program works perfectly, and passes every test, right up until it has been running long enough to matter. A leak of forty bytes in a function called once is invisible forever; the same forty bytes in a loop that runs a million times an hour is a server that falls over every Tuesday night.
Two things make leaks unusually nasty in C++. First, the symptom appears nowhere near the cause — memory runs out in whatever code happens to allocate next, so the stack trace points at an innocent bystander. Second, the process is the only cleanup mechanism: the operating system reclaims everything when your program exits, which means short-lived programs leak harmlessly and you never learn that you were doing it.
The good news is that leaks are the single most solved problem in modern C++. Every leak in this lesson is prevented, not detected, by applying the previous two lessons: put the resource in an owner object. The point of studying leaks directly is to recognise them in code you did not write, and to know which tool finds the ones already in your codebase.
Syntax or Core Structure
#include <iostream>
#include <memory>
#include <string>
#include <vector>
// LEAK 1: no delete at all.
void forgotten() {
int* p = new int(42);
std::cout << *p << "\n";
// 4 bytes lost, permanently
}
// LEAK 2: an early return jumps over the delete.
void earlyExit(bool bail) {
int* buffer = new int[1000];
if (bail) {
return; // 4000 bytes lost
}
delete[] buffer;
}
// LEAK 3: overwriting the only pointer to a block.
void overwritten() {
int* p = new int(1);
p = new int(2); // the first block is now unreachable
delete p; // frees the second only
}
// LEAK 4: wrong delete form -- destructors skipped.
void wrongForm() {
std::string* names = new std::string[3]{"Ada", "Grace", "Alan"};
delete names; // only names[0] destroyed; buffers leak
}
// LEAK 5: leaking in a loop -- the dangerous one.
void inALoop() {
for (int i = 0; i < 100000; ++i) {
double* sample = new double(i * 0.5);
// no delete: 800 kB gone in a fraction of a second
}
}
// FIXED: the same five, with nothing to forget.
void fixed(bool bail) {
int value = 42; // stack: no allocation
std::cout << value << "\n";
std::vector<int> buffer(1000); // frees itself
if (bail) return; // no leak
auto p = std::make_unique<int>(1);
p = std::make_unique<int>(2); // reassigning FREES the old
std::vector<std::string> names{"Ada", "Grace", "Alan"};
for (int i = 0; i < 100000; ++i) {
double sample = i * 0.5; // stack, per iteration
}
}
Look at what the fixed version does not contain: no new, no delete, no cleanup on the early return, and no way to get the array form wrong. Leaks are prevented by not writing the code that leaks.
Technical Depth: Every Way to Leak, and How to Find Them
The exception path is the one you cannot see
void looksFine() {
Widget* w = new Widget();
w->configure(); // if THIS throws, the delete is skipped
process(w); // or this
delete w;
}
This function is correct today and leaks tomorrow, the moment anyone adds a throw to configure or process — without your file being edited. That is why "just be careful with delete" is not a strategy: correctness depends on code you do not control.
Leaking a member, and forgetting the destructor
class Session {
int* data;
public:
Session() : data(new int[100]) {}
// NO DESTRUCTOR -- every Session ever created leaks 400 bytes
};
Then the subtler version, where the destructor exists but copying does not:
class Session {
int* data;
public:
Session() : data(new int[100]) {}
~Session() { delete[] data; }
// implicit copy copies the POINTER
};
std::vector<Session> sessions;
sessions.push_back(Session()); // copy made, original destroyed -> DOUBLE FREE
The rule of three exists for exactly this. Either implement copy properly, delete it, or — far better — hold a std::vector<int> and delete nothing.
The missing virtual destructor
class Base {
public:
~Base() { } // NOT virtual
};
class Derived : public Base {
std::vector<int> big{10000};
public:
~Derived() { }
};
Base* p = new Derived();
delete p; // only ~Base runs -- the vector leaks
This one leaks a lot, quietly, and it is undefined behaviour besides. Any class you might delete through a base pointer needs virtual ~Base() = default; — and a unique_ptr<Base> does not save you, because it calls the same delete.
The shared_ptr cycle
The one leak smart pointers do not prevent:
struct Node {
std::shared_ptr<Node> other;
};
auto a = std::make_shared<Node>();
auto b = std::make_shared<Node>();
a->other = b;
b->other = a; // each holds the other's count at 1
// both scope out -- neither reaches 0 -- both leak
Reference counting cannot see a cycle. Break it by making one direction std::weak_ptr, and remember the rule: ownership points one way.
Leaks that are not memory
The same discipline applies to every finite resource, and these are often worse because the limits are much lower — a few thousand file descriptors, not gigabytes:
| Resource | Leaked by | Symptom |
|---|---|---|
| File handles | fopen without fclose | "too many open files" |
| Sockets | socket without close | Connections refused |
| Mutex locks | lock() without unlock() | Deadlock |
| Database connections | Not returning to the pool | Pool exhausted |
| OS handles | CreateX without CloseHandle | Handle-count growth |
| Threads | Never joined or detached | Resource exhaustion |
std::lock_guard, std::ifstream and std::jthread exist so that these become impossible in the same way.
Growth is not always a leak
Not every rising memory graph is a bug:
std::vector<int> v;
for (int i = 0; i < 1000000; ++i) v.push_back(i); // grows, but owns it all
That is memory use, not a leak — every byte is reachable and will be freed. A cache that never evicts is a design flaw rather than a leak. And allocators legitimately hold freed memory back from the OS for reuse, so process memory can stay flat-high after a burst. The test for a leak is reachability: is there still a pointer to it? If not, it has leaked.
Fragmentation is a third, distinct thing: many small allocations and frees can leave the heap unable to satisfy a large request even with plenty of free bytes. Fewer, larger allocations — which containers do naturally — mitigate it.
Finding leaks: the tools
AddressSanitizer is the first thing to try. It is built into GCC and Clang, needs no separate program, and slows execution by roughly 2×:
g++ -fsanitize=address -g -O1 main.cpp -o main
./main
On exit it prints a report naming the allocation site:
==1234==ERROR: LeakSanitizer: detected memory leaks
Direct leak of 4000 byte(s) in 1 object(s) allocated from:
#0 0x... in operator new[](unsigned long)
#1 0x... in earlyExit(bool) main.cpp:12
Valgrind needs no recompilation and finds more, at roughly 20× slowdown:
g++ -g main.cpp -o main
valgrind --leak-check=full --show-leak-kinds=all ./main
| Tool | Platform | Needs rebuild | Cost | Also finds |
|---|---|---|---|---|
| AddressSanitizer | Linux, macOS, Windows (Clang/MSVC) | Yes | ~2× | Overflows, use-after-free |
| Valgrind | Linux, macOS | No | ~20× | Uninitialised reads |
| Dr. Memory | Windows, Linux | No | ~10× | Similar to Valgrind |
| Visual Studio CRT | Windows/MSVC | Yes | Low | Allocation numbers |
static_analyzer / clang-tidy | Any | No | Compile time | Suspicious patterns, before you run |
Valgrind's report distinguishes leak kinds that matter: definitely lost is a real leak with no pointer to it; still reachable means it was never freed but a pointer existed at exit, which is usually a global and usually harmless.
Run these in CI, not just when you suspect something. A leak check on your test suite catches the problem in the commit that introduced it, when you still know why the code looks like that.
The prevention checklist
| If you write | You have taken on | Prefer |
|---|---|---|
new | A matching delete on every path | make_unique |
new[] | A matching delete[] | std::vector |
| A raw owning member | A destructor, plus rule of three | A self-managing member |
| A polymorphic base | virtual ~Base() | The same, no alternative |
shared_ptr both ways | A cycle | weak_ptr one way |
fopen, lock, socket | A matching release on every path | ifstream, lock_guard, a wrapper |
Read down the right-hand column: it is the whole of leak prevention, and there is no discipline required at the call site for any of it.
Real World Example: Auditing a Leaky Plugin Host
Below is the kind of code you inherit: a plugin host that works, ships, and slowly eats memory. It contains six distinct leaks, each of a different species from the section above. Read it first and try to find them before reading the fixed version — this is the skill the lesson is actually for.
// ============ BEFORE: six leaks ============
#include <cstdio>
#include <iostream>
#include <map>
#include <string>
#include <vector>
class Plugin {
public:
explicit Plugin(std::string n) : pluginName(std::move(n)) {}
~Plugin() {} // LEAK 4: not virtual
virtual void run() { std::cout << pluginName << " ran\n"; }
const std::string& name() const { return pluginName; }
private:
std::string pluginName;
};
class HeavyPlugin : public Plugin {
public:
HeavyPlugin() : Plugin("heavy"), workspace(new double[100000]) {}
~HeavyPlugin() { delete[] workspace; }
void run() override { std::cout << "heavy ran\n"; }
private:
double* workspace;
};
class Host {
public:
void load(Plugin* p) {
plugins.push_back(p); // raw ownership, unclear
}
void loadConfig(const char* path) {
std::FILE* f = std::fopen(path, "r");
if (!f) return;
char line[128];
while (std::fgets(line, sizeof(line), f)) {
if (line[0] == '#') return; // LEAK 2: f never closed
settings[line] = true;
}
std::fclose(f);
}
void runAll() {
for (Plugin* p : plugins) {
int* scratch = new int[256]; // LEAK 5: never freed
p->run();
}
}
void reset() {
plugins.clear(); // LEAK 1: pointers dropped
}
~Host() {
// LEAK 6: nothing deleted at all
}
private:
std::vector<Plugin*> plugins;
std::map<std::string, bool> settings;
};
int main() {
Host host;
host.load(new Plugin("basic"));
host.load(new HeavyPlugin()); // LEAK 3 via non-virtual dtor
host.runAll();
host.reset();
return 0;
}
Six leaks, all of them silent. Under AddressSanitizer this program reports roughly 800 kB lost across five allocation sites; run runAll in a service loop and the scratch array alone consumes a kilobyte per plugin per iteration forever.
Now the same program with nothing to forget:
// ============ AFTER: no raw ownership anywhere ============
#include <algorithm>
#include <fstream>
#include <iostream>
#include <map>
#include <memory>
#include <string>
#include <vector>
class Plugin {
public:
explicit Plugin(std::string n) : pluginName(std::move(n)) {}
virtual ~Plugin() = default; // FIX 4: virtual
virtual void run() { std::cout << pluginName << " ran\n"; }
const std::string& name() const { return pluginName; }
private:
std::string pluginName;
};
class HeavyPlugin : public Plugin {
public:
HeavyPlugin() : Plugin("heavy"), workspace(100000) {} // FIX 3: a vector
void run() override { std::cout << "heavy ran\n"; }
private:
std::vector<double> workspace; // no destructor needed
};
class Host {
public:
void load(std::unique_ptr<Plugin> p) { // FIX: ownership in the API
plugins.push_back(std::move(p));
}
bool loadConfig(const std::string& path) {
std::ifstream in(path); // FIX 2: closes itself
if (!in) return false;
std::string line;
while (std::getline(in, line)) {
if (line.empty() || line[0] == '#') continue; // and don't bail early
settings[line] = true;
}
return true;
}
void runAll() {
std::vector<int> scratch(256); // FIX 5: reused, self-freeing
for (const std::unique_ptr<Plugin>& p : plugins) {
std::fill(scratch.begin(), scratch.end(), 0);
p->run();
}
}
void reset() {
plugins.clear(); // FIX 1: destroys each plugin
}
std::size_t count() const { return plugins.size(); }
// FIX 6: no destructor at all -- the rule of zero
private:
std::vector<std::unique_ptr<Plugin>> plugins;
std::map<std::string, bool> settings;
};
int main() {
Host host;
host.load(std::make_unique<Plugin>("basic"));
host.load(std::make_unique<HeavyPlugin>());
std::cout << "loaded " << host.count() << " plugins\n";
host.runAll();
host.reset();
std::cout << "after reset: " << host.count() << " plugins\n";
}
Output:
loaded 2 plugins
basic ran
heavy ran
after reset: 0 plugins
Under AddressSanitizer: no output at all, which is the report you want.
Take the six in turn, because each illustrates a different failure mode. Leak 1 is plugins.clear() on a std::vector<Plugin*>: the vector dutifully destroys its elements, and destroying a pointer does nothing. The container was never the owner. Changing the element type to std::unique_ptr<Plugin> makes clear() mean what the author obviously thought it meant, and that is the entire fix — the call site did not change.
Leak 2 is the classic early return, and note that the fclose at the bottom is present and correct. The bug is a return above it on a path the author added later for a comment line. std::ifstream removes the possibility rather than the mistake; the continue instead of return fixes a second, unrelated bug in the same line.
Leaks 3 and 4 are one bug seen from two sides. HeavyPlugin owns 800 kB and frees it correctly in its own destructor — which never runs, because delete through a Plugin* with a non-virtual destructor only calls ~Plugin. Adding virtual fixes it; replacing the raw array with std::vector<double> means HeavyPlugin needs no destructor at all, so there is nothing left to skip. Doing both is right: the virtual is required by the polymorphic design regardless of what the members are.
Leak 5 is the one that actually takes servers down. A single 1 kB allocation is nothing; inside a loop that runs per plugin per request it is unbounded growth. The fix is not to add a delete — it is to notice that scratch did not need to be per-iteration at all, and hoisting it out of the loop removes both the leak and the allocation cost.
Leak 6 is the absent destructor, and the fix is the most instructive: the after version has no destructor, and is correct precisely because of that. Once plugins is a vector<unique_ptr<Plugin>> and settings is a map, the compiler-generated destructor does exactly the right thing. Writing one by hand would have been a chance to get it wrong.
The pattern across all six is worth stating: not one fix was "remember to free it". Every fix changed a type so that freeing became automatic. That is why leak prevention in modern C++ is a design activity rather than a discipline — and why grepping a codebase for new, delete and fopen is such a good first pass when auditing one.
Common Mistakes
- Assuming a short-lived program's leaks do not matter. They do not — until that code is reused in a long-running one.
clear()on a container of raw pointers. It destroys pointers, not objects. Store smart pointers.- Trusting the delete at the bottom of the function. Any
returnorthrowabove it skips it. - Omitting
virtualon a base destructor. Deleting through the base pointer skips the derived destructor entirely. - Writing a destructor but not handling copies. Rule of three; otherwise a double free or a leaked copy.
- Reassigning a raw pointer.
p = new T();twice loses the first block forever. - Mutual
shared_ptrreferences. A cycle no reference count can break. Useweak_ptrone way. - Allocating inside a loop. The smallest per-iteration leak becomes the largest total one.
- *Only checking for memory leaks.* File handles, sockets, locks and connections have much smaller limits.
- Concluding "no crash, no leak". Leaks never crash at the site of the bug, and often not at all.
- Only running a leak checker when something looks wrong. Put it in CI so the failing commit is obvious.
- Treating growing memory as automatically a leak. Check reachability; a cache or an allocator holding memory back is not the same thing.
Best Practices
- Do not write
newordelete. Use containers, thenmake_unique. Every leak in this lesson becomes unwritable. - Make ownership explicit in your signatures.
void load(std::unique_ptr<Plugin>)documents and enforces the transfer;void load(Plugin*)documents nothing. virtual ~Base() = default;on every polymorphic base, without exception.- Aim for the rule of zero — if you need no destructor, you cannot forget one.
- Hoist allocations out of loops, both for leaks and for speed.
- Use
weak_ptrfor back-references so ownership only ever points one way. - Wrap every non-memory resource in RAII too — files, sockets, locks, handles.
- Build with
-fsanitize=addressin development and CI, and run Valgrind before a release. - Enable warnings and clang-tidy.
-Wall -Wextraand thecppcoreguidelines-owning-memorycheck catch some of this before it runs. - When auditing unfamiliar code, grep for
new,delete,fopenandlockfirst. The leaks are almost always within a few lines.
Practice Exercises
- Write a program with a deliberate leak in a loop, build it with
-fsanitize=address, and read the report. Identify the exact line it names, fix the leak with astd::vector, and confirm the report goes quiet. - Take the "before"
Hostclass from this lesson and fix all six leaks yourself without looking at the "after" version. Then compare, and for each fix note whether you added cleanup code or changed a type — and which of the two you would rather review in a pull request. - Write
bool importRecords(const std::string& path)that allocates a buffer withnew, then leaves the function through four different routes: a successfulreturn true, two earlyreturn falseguards for a missing file and an empty file, and athrow std::runtime_errorfor a malformed row. Put a singledelete[]before the successful return only, then count the leaks by calling the function once for each route under a leak checker. Fix it twice — first by adding cleanup to every exit path, then by throwing the manual buffer away entirely — and compare how many lines each version needs and how many exits a future fifthreturnwould have to remember.