Address and Leak Sanitizers for C++

Posted on Oct 23, 2022

You heard that in C++ there’s always the risk to leak memory, and now you’re wondering if there is a tool that can help you find if your program contains memory leaks? Luckily, there are some tools, such as the LeakSanitizer.

First of all, this is something done at runtime - this sort of functionality won’t be able to find your memory leaks at build time, unfortunately. You can use the AddressSanitizer to help you find memory errors, which might include things that lead to memory leaks, but the leak sanitizer is explicitly made for finding memory leaked at runtime.

Now, even though it’s a runtime functionality, you will still need to tell your compiler to activate the sanitizer at build time. There are several options to do so.

As I follow a lot the cpp-best-practices/gui_starter_template, I take advantage of the ENABLE_DEVELOPER_MODE CMake variable that will instruct project_options to enable sanitizers for me. However, all you need in theory is really just to set the flag -fsanitize=address at compilation time - beware that Apple Clang, as of version 14.0.0, does not support yet this sanitizer (you’ll need clang or gcc, take a look here to see how to install them).

Finally, as this is a runtime option, and you will need to set a variable to tell the sanitizer that you want to use a specific feature, in this case the “detect_leaks=1”. In order to do so, you’ll need to set the LSAN_OPTIONS* before executing your program, e.g.,

LSAN_OPTIONS="detect_leaks=1" ./bin/app

At the end of the program, the leak detector will give you some warnings if there were memory leaks found.

Note: In CLion, you can set sanitizer flags in Preferences | Build, Execution, Deployment | Dynamic Analysis Tools | Sanitizers.

Now, when you run the program in the IDE, the variable will be set, and at the end of the program, you will get some feedback if some memory leaks were found.