Dynamic memory in C++ is managed in the heap, which new
and delete
use. Misuse of new
and delete
can lead to memory management problems.
The tool valgrind is a platform for dynamic analysis tools that detect multiple issues in a running program. The specific tool in valgrind for detecting memory management problems is memcheck.
The following describes using valgrind on a single-file program Memory.cpp. You can use valgrind with GitHub Codespaces, install it in Ubuntu in Linux or WSL (sudo apt install valgrind
), or install Docker in macOS. Note: valgrind in macOS does not work. You can also view a screencast of the following steps.
Before you run valgrind, you need a Debug compile of the program:
The -g
command for the compiler is for debug. It adds source-code line number information into the executable program. The debug option on the compiler allows Valgrind to refer to specific line numbers in your code.
To get a debug build of your program with CMake, you need to set the CMAKE_BUILD_TYPE
to Debug
:
Valgrind has many tools with complex options. To run valgrind for detecting memory issues:
Valgrind produces an overwhelming amount of output. The important information is at the end. The interesting parts of the output are the HEAP SUMMARY:, LEAK SUMMARY, and ERROR SUMMARY. An unsuccessful run with memory leaks of Valgrind ends with something like this:
A successful run with no memory leaks of Valgrind ends with something like this:
If Valgrind does not show a memory leak, that does not mean the program is free of memory leaks. It means that, in that specific case, a memory leak was not detected. If the input or options to the program change, there could still be a memory leak.