Valgrind1 is a command line suite of tools to check for memory leaks in code (among other things), especially in memory-unsafe languages like C or C++. It instruments the heap and checks when we allocate or free memory, then tells us what we didn’t free.
Tools
- Memcheck is the main tool we use with Valgrind. It checks for errors in memory allocation and accesses (so it catches things like segfaults).
- Cachegrind simulates CPU cache accesses, including for L1 (instruction-level I1 and data-level D1) and L2 caches. The point of this is to check for cache misses in our code.
- Massif profiles the heap and shows dynamic heap allocation at a given moment.
- Helgrind is a tool to detect threading errors.
- Callgrind is a profiler that is able to provide an exact call graph. It reports performance in number of instructions instead of actual execution time.
The basics
We need a valid executable before using Valgrind. It’s best practice to compile in a “debug” mode, whether in a Make or with compilers like G++. This allows the tool to show the function names and line numbers where errors occur (but the line number may not be entirely accurate):
make config="debug"
g++ -g filename.cpp -o exename
Then we use Valgrind on the executable with valgrind ./exename
. The leak-check
flag is an important tool to use. Memcheck is the main tool we use to check for errors in memory allocation and access.2
Flags
--leak-check=full
: provide detailed information on the memory leaks instead of just a summary.--log-file=file-name
: save the output to the file specified.--tool=
: run Valgrind using a different tool than Memcheck.