Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I make LeakSanitizer ignore end of program leaks

I want to use LeakSanitizer to detect leaked memory, but the style of the program I am using does not free memory before exit. This is fairly common in my experience.

I want to detect this leak:

int main(int argc, char const *argv[])
{
    char *p = malloc(5);
    p = 0;
    return 0;
}

And ignore this leak:

int main(int argc, char const *argv[])
{
    char *p = malloc(5);
    return 0;
}
like image 492
Evan Benn Avatar asked Jul 27 '18 07:07

Evan Benn


1 Answers

You want LSan to report only unreachable leaks i.e. pointers which are guaranteed to be leaked by the program. Problem is that by default LeakSanitizer runs it's checks at the end of the program, often after global C++ dtors have completed and their contents is no longer considered accessible. So when LSan finally runs, it has to assume that lots of stuff is no longer reachable. To work around this issue you can add

#include <lsan_interface.h>
...
#ifdef __SANITIZE_ADDRESS__
  __lsan_do_leak_check();
  __lsan_disable();
#endif

before returning from main (inspired by Issue 719 and llvm discussion).

PS: Be careful with extremely simple examples like the ones you post above. GCC will often remove unused assignments and allocations even at -O0 so always check that assembler matches your expectations.

like image 75
yugr Avatar answered Nov 14 '22 20:11

yugr