Many code languages don’t have garbage collection and also suffer from issues like uninitialized variables etc. CMake can use several common tools to check memory usage of a program. These tools are limited by the code coverage of the tests run.
The basic procedure is to build the project in “Debug” mode, run CTest memcheck task, then browse the results. Then fix the problems and rerun the tests to verify.
The popular “valgrind” memory tester is available on Linux, including Windows Subsystem for Linux (WSL). CMake will usually automatically detect valgrind if the valgrind executable is on the environment variable PATH. That is, if typing “valgrind” at the Terminal runs, then CMake should find and use it.
To use memory checking tools from CMake, the CMakeLists.txt must include the line:
Here are example CMake commands to check memory of a project.
cmake -Bbuild -DCMAKE_BUILD_TYPE=Debug cmake --build build ctest -T memcheck --test-dir build
The tests may run more slowly than usual due to the testing overhead. The CTest terminal output will look like:
MemCheck log files can be found here: (<#> corresponds to test number) build/Testing/Temporary/MemoryChecker.<#>.log Memory checking results: Memory Leak - 8 Potential Memory Leak - 8 Uninitialized Memory Conditional - 3
Each MemCheck CTest number has a log file. The traceback stack to the suspected area (line) of code detected to lead to memory problems is given. Edit the code to fix the problem, then rebuild and rerun memcheck as above.
Configure CTest memcheck
To change from default CTest memcheck settings, create a script memcheck.cmake in the top level of the project (where the top CMakeLists.txt is). Run this script like:
ctest -S memcheck.cmake -V
valgrind -gen-suppressions=all <executable>