如何在编译时启用Leak Sanitizer?

时间:2015-07-07 15:30:36

标签: c memory-leaks sanitizer address-sanitizer leak-sanitizer

GCC和Clang编译器都支持LeakSanitizer,这有助于在C程序中查找内存泄漏。有时内存泄漏是不可避免的(因为它正在测试套件中进行测试)。

可以使用Leak Sanitizer interface

注释此类内存
#include <sanitizer/lsan_interface.h>

void *p = create_new_object();
__lsan_ignore_object(p);

然而,这将在不支持LSan的编译器上中断。在Address Sanitizer中,此构造可用于检测ASAN的可用性:

/* __has_feature(address_sanitizer) is used later for Clang, this is for
 * compatibility with other compilers (such as GCC and MSVC) */
#ifndef __has_feature
#   define __has_feature(x) 0
#endif

#if __has_feature(address_sanitizer) || defined(__SANITIZE_ADDRESS__)
    /* ASAN-aware code here. */
#endif

没有__has_feature(leak_sanitizer)来检测Clang中是否存在LSan,GCC也不存在__SANITIZE_LEAKS__。如何检测ASAN可用性?请注意,可以独立于AddressSanitizer和ThreadSanitizer启用LSan。

1 个答案:

答案 0 :(得分:3)

由于编译器没有为自己设置预处理器定义,因此必须为自己设置。

使用LeakSanitizer或不使用LeakSanitizer进行-fsanitize=leak -DMYLEAKSAN=1编译,使用-DMYLEAKSAN=0进行编译。如果忘记定义MYLEAKSAN,则编译器将暂停。

#ifndef MYLEAKSAN
#   error: MYLEAKSAN must be either 0 or 1
#endif
#include <stdio.h>
#include <stdlib.h>
#if MYLEAKSAN
#   include <sanitizer/lsan_interface.h>
#endif

int main(void)
{
    void *p = malloc(5);
#if MYLEAKSAN
    __lsan_ignore_object(p);
#endif
}