我怎么知道在编译时是否启用了Leak Sanitizer? [英] How can I know if Leak Sanitizer is enabled at compile time?
问题描述
GCC和Clang编译器均支持 LeakSanitizer ,这有助于在C程序中查找内存泄漏.有时,内存泄漏是不可避免的(例如,正在测试套件中对其进行测试).
The GCC and Clang compilers both have support for LeakSanitizer which helps finding memory leaks in C programs. Sometimes a memory leak is unavoidable (because it is being tested in a test suite for example).
可以使用泄漏来注释此类内存.消毒器界面:
#include <sanitizer/lsan_interface.h>
void *p = create_new_object();
__lsan_ignore_object(p);
但是,这将在不支持LSan的编译器上中断.在Address Sanitizer中,此构造可用于检测ASAN的可用性:
This will however break on compilers that do not support LSan. In Address Sanitizer, this construct can be used to detect the availablity of 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的存在,并且__SANITIZE_LEAKS__
对于GCC都不存在.无论如何,我如何检测ASAN的可用性?请注意,可以独立于AddressSanitizer和ThreadSanitizer启用LSan.
There is no __has_feature(leak_sanitizer)
to detect just the existence of LSan in Clang and neither does __SANITIZE_LEAKS__
exist for GCC. How can I detect ASAN availability anyway? Note that LSan can be enabled independently of AddressSanitizer and ThreadSanitizer.
推荐答案
由于编译器没有为自己设置预处理器定义,因此必须自己完成.
As the compiler does not set a preprocessor define for itself one have to do that for himself.
使用LeakSanitizer在带有-fsanitize=leak -DMYLEAKSAN=1
的情况下进行编译,或者在没有LeakSanitizer的情况下使用-DMYLEAKSAN=0
的情况进行编译.如果确实忘记定义MYLEAKSAN
,则编译器将暂停.
One compile with -fsanitize=leak -DMYLEAKSAN=1
with LeakSanitizer or without LeakSanitizer one compile with -DMYLEAKSAN=0
. If one does forget to define MYLEAKSAN
the compiler is halted.
#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
}
这篇关于我怎么知道在编译时是否启用了Leak Sanitizer?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!