When tracking down memory corruption, buffer overflows, or use-after-free issues in C++ programs, AddressSanitizer (ASan) is one of the most effective diagnostic tools available. There are situations where software may need to detect whether it was compiled with AddressSanitizer enabled. This can be useful for turning on additional diagnostics, bypassing performance-critical routines, or adjusting behavior that might interfere with sanitization. This tutorial shows how to check if application is compiled with AddressSanitizer using C++.
To determine whether the program was built with AddressSanitizer, you can rely on compiler-provided feature checks and predefined macros. The behavior differs slightly between Clang and GCC:
- Clang offers the
__has_feature(address_sanitizer)test. This allows you to detect AddressSanitizer support during compilation and define the own macro if needed. - GCC, on the other hand, does not support
__has_feature. Instead, GCC automatically defines the macro__SANITIZE_ADDRESS__when the-fsanitize=addressoption is used. Clang does not define this macro by default.
Because of this difference, we can write a small compatibility layer that works across both compilers:
#include <iostream>
#ifdef __has_feature
#if __has_feature(address_sanitizer)
#define __SANITIZE_ADDRESS__
#endif
#endif
#ifdef __SANITIZE_ADDRESS__
#define USING_ASAN 1
#else
#define USING_ASAN 0
#endif
int main() {
if (USING_ASAN) {
std::cout << "Using AddressSanitizer" << std::endl;
} else {
std::cout << "Not using AddressSanitizer" << std::endl;
}
return 0;
}
To compile the program with AddressSanitizer enabled, pass the appropriate option to the compiler:
g++ main.cpp -fsanitize=address -o test
Run the binary:
./test
When AddressSanitizer is present, the output will indicate that the binary was built with AddressSanitizer. Otherwise, it confirms a normal, non-sanitized build.
Leave a Comment
Cancel reply