如何使LeakSanitizer忽略程序泄漏的结束

时间:2022-01-01 07:20:26

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.

我想使用LeakSanitizer来检测泄漏的内存,但我使用的程序的样式在退出之前不会释放内存。这在我的经历中相当普遍。

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 个解决方案

#1


3  

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

您希望LSan仅报告无法访问的泄漏,即保证程序泄露的指针。问题是默认情况下LeakSanitizer在程序结束时运行它的检查,通常是在全局C ++ dtors完成后,它们的内容不再被认为是可访问的。因此,当LSan最终运行时,它必须假设许多东西不再可达。要解决此问题,您可以添加

#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).

在从main返回之前(受问题719和llvm讨论的启发)。

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.

PS:请注意上面提到的非常简单的例子。即使在-O0,GCC也会经常删除未使用的分配和分配,因此请始终检查汇编程序是否符合您的期望。

#1


3  

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

您希望LSan仅报告无法访问的泄漏,即保证程序泄露的指针。问题是默认情况下LeakSanitizer在程序结束时运行它的检查,通常是在全局C ++ dtors完成后,它们的内容不再被认为是可访问的。因此,当LSan最终运行时,它必须假设许多东西不再可达。要解决此问题,您可以添加

#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).

在从main返回之前(受问题719和llvm讨论的启发)。

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.

PS:请注意上面提到的非常简单的例子。即使在-O0,GCC也会经常删除未使用的分配和分配,因此请始终检查汇编程序是否符合您的期望。