How do I make LeakSanitizer ignore end of program leaks

天大地大妈咪最大 提交于 2019-12-09 13:33:09

问题


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;
}

回答1:


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.



来源:https://stackoverflow.com/questions/51553115/how-do-i-make-leaksanitizer-ignore-end-of-program-leaks

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!