Detecting and preventing the memory leaks in C++ is a two-part job. A tool tells you that the memory was lost, and a set of habits stops it from happening. The address sanitizer finds most of the leaks with no extra tooling at all, and the habits are mostly about ownership, which means making it obvious who is responsible for each allocation so that a leak becomes impossible rather than merely unlikely.
The previous lesson in this module covered "Why Do unique_ptr and shared_ptr Replace Manual delete?", and the next lesson in this module is about "What Is RAII and Why Is It C++'s Core Habit?".
What a leak actually is
A leak happens when the memory is still allocated at the moment that the program ends. The program does not crash. It just quietly uses more and more memory, and on a long-running server that eventually brings the machine down.
#include <iostream>
int* allocate_and_forget() {
int* block = new int[1000];
block[0] = 1;
return block; // the pointer is lost here
}
int main() {
for (int i = 0; i < 100; ++i) {
allocate_and_forget();
}
std::cout << "program finished normally\n";
return 0;
}The program prints one cheerful line and it exits with status zero. A hundred thousand integers are gone, and nothing in the output says so.
The address sanitizer finds leaks for you
Adding -fsanitize=address to the compile and the link step turns on a runtime checker that reports the leaks at the exit.
g++ -std=c++17 -Wall -Wextra -g -fsanitize=address leak.cpp -o leak
./leakAnd the report names the allocation site and not the place where the memory was lost, which is usually what you need.
=================================================================
==12345==ERROR: LeakSanitizer: detected memory leaks
Direct leak of 4000 byte(s) in 1 object(s) allocated from:
#0 0x7f... in operator new(unsigned long)
#1 0x55... in allocate_and_forget() leak.cpp:5
#2 0x55... in main() leak.cpp:12
SUMMARY: AddressSanitizer: 4000 byte(s) leaked in 100 allocation(s).
=================================================================The three lines of the trace are the whole story. The allocation happened in allocate_and_forget on line 5, and that was called from main on line 12. The fix is at the top of that trace and not at the bottom.
The leak checker in the standard library
The C++ standard library ships its own leak detector for the containers that it owns. When a container is destroyed while it still holds the elements, the library prints a warning.
#include <iostream>
#include <memory>
struct Widget {
explicit Widget(int id) : id(id) {}
~Widget() {
std::cout << "destroying widget " << id << '\n';
}
int id;
};
int main() {
auto leaked = std::make_unique<int[]>(10);
leaked[0] = 1;
std::cout << "allocated\n";
return 0;
}The output is clean, because the unique pointer released the array.
allocatedAnd the library's own check is triggered when a container is allocated with new and never deleted, which is why the advice is always the same. Let a smart pointer own it.
Valgrind for the harder cases
Valgrind runs your program under the instrumentation and it reports the leaks, the invalid reads, the invalid writes and the use of the uninitialised values. It is slower than the sanitizer, but it needs no recompilation.
valgrind --leak-check=full --show-leak-kinds=all ./programAnd the output separates the leaks into categories. The definitely lost ones are the blocks that nothing points at any more. The indirectly lost ones are the blocks that are only reachable through other leaked blocks. And the still reachable ones are the blocks that are probably held by a global pointer that is never freed.
And the still reachable category is where most people's first reaction is "that is a leak too". It usually is not. A pointer that is stored in a global and that lives for the whole program is reachable, and whether that is a problem depends on your design.
Reading a leak report
A leak report is a stack trace of the allocation. Reading it means finding the frame in your own code, and the frames above it are usually the library internals that you can ignore.
the category what it means
------------------------ ----------------------------------------------
directly lost the block was allocated and nothing points
at it any more
indirectly lost the block is only reachable through
another leaked block
still reachable something still points at it, but the
pointer is probably a global
possibly lost an interior pointer exists, so the tool
cannot prove that it is unreachable
Habits that prevent leaks
The reliable way to avoid the leaks is to remove the decisions.
Prefer the automatic storage. A local variable is freed at the end of its scope without any thought at all. Use a smart pointer for every dynamic allocation, because a std::unique_ptr makes the leak impossible, since the compiler will not let the ownership be ambiguous. And do not return raw pointers, because a function that returns a raw pointer has to document who deletes the result, and that documentation is the first thing to go stale.
#include <iostream>
#include <memory>
struct Widget {
explicit Widget(int id) : id(id) {}
int id;
};
std::unique_ptr<Widget> make_widget(int id) {
return std::make_unique<Widget>(id);
}
int main() {
auto widget = make_widget(7);
std::cout << "widget id: " << widget->id << '\n';
return 0;
}The output shows the widget being created and cleaned up automatically.
widget id: 7And two more rules. Do not delete something that you did not allocate, because a double free is as bad as a leak and the sanitizer reports both. And keep the ownership obvious in the signature. A function that takes a std::unique_ptr<T> takes the ownership, and a function that takes a T& or a const T& borrows it. The parameter type is the documentation.
A leak checklist
- Build your tests with
-fsanitize=addressfrom the start. - Read the first leak report completely before you fix anything.
- Fix the leaks at the allocation site and not at the exit point.
- Treat the definitely lost and the indirectly lost blocks as bugs.
- Investigate the still reachable blocks before you decide that they are harmless.
- Never suppress a leak report without understanding it first.
- Make the ownership visible in every function signature.
Quick reference
- A leak is memory that is still allocated when the program ends, and the program does not crash.
- The
-fsanitize=addressflag reports the leaks at the exit and it names the allocation site. - Valgrind finds the leaks without a recompilation, and it also catches the invalid memory access.
- The leaks are directly lost, indirectly lost, still reachable or possibly lost.
- The automatic storage and the smart pointers remove the possibility of a leak.
- The ownership belongs in the function signature. A
std::unique_ptrowns, and a reference borrows.
Try it yourself: write a program that allocates the memory in a loop and loses the pointers, and then build it with -fsanitize=address and read the report. Fix the leak by using a container or a smart pointer and rebuild. Finally, introduce a double free instead and confirm that the sanitizer reports that as well, with a different message.