Valgrind

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.

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.

If you are using a cmake build, you can create a debug build with the following:

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: