Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

does leak sanitizer guarantee absence of memory leaks?

If I compile a c++ program using the -fsanitize=leak flag, does this guarantee absence of memory leaks at runtime?

Or where are some more stronger leak check tool(except valgrind)?

like image 280
artem zholus Avatar asked Oct 18 '25 13:10

artem zholus


2 Answers

Short answer: No.

There is no guarantee the sanitizer will detect every possible leak. Nor is there a guarantee the compiler will warn about all leaks. Nor is it guaranteed that Valgrind will spot all leaks.

The tools try their best in different ways but they all have limitations (and bugs).

For example;

The compiler can only warn about leaks it can detect by analyzing your source code (and it also has an upper bound on how much time it can reasonably spend on that).

The sanitizer can only detect bugs it was written to test for - and then, it will only detect them in code you actually execute. So if a specific run of your application only exercises 50 percent of the code and the leak is in the other half it is not going to see it.

Likewise, Valgrind can only detect leaks it was designed to detect and it doesn't have access to the source, nor the benefit of compiler instrumentation and it can also only see leaks in code that actually runs.

So no. The tools not flagging any leaks does not prove the absence of leaks. That would require formal proof of correctness of not just your code but also everything it depends on (like the standard library for example) and this is not a solved problem for real-world programs.

Your best bet is to run a number of different tools and fix what they find and try to write your code carefully and deliberately and know what you are doing.

like image 82
Jesper Juhl Avatar answered Oct 20 '25 03:10

Jesper Juhl


... does this guarantee absence of memory leaks at runtime?

Well, -fsanitize might call for overshooting expectations from the wording. The feature doesn't really sanitize the code from having problems with memory leaks, but helps to detect them.


As from the GCC documentation:

-fsanitize=leak
       Enable LeakSanitizer, a memory leak detector.  This option only
       matters for linking of executables and if neither
       -fsanitize=address nor -fsanitize=thread is used.  In that case
       the executable is linked against a library that overrides
       "malloc" and other allocator functions.  See
       <https://github.com/google/sanitizers/wiki/AddressSanitizerLeakSanitizer >
       for more details.  The run-time behavior can be influenced using
       the LSAN_OPTIONS environment variable.
like image 27
πάντα ῥεῖ Avatar answered Oct 20 '25 04:10

πάντα ῥεῖ