How do I use sanitizers (ASan, UBSan, TSan, MSan)?

Sanitizers are powerful debugging tools that help identify various types of errors in C++ programs. Here’s a brief overview of the different sanitizers you can use in your C++ projects:

AddressSanitizer (ASan)

AddressSanitizer is used to detect memory corruption errors such as buffer overflows and use-after-free errors. To compile your code with ASan, use the following flags:

g++ -fsanitize=address -g my_program.cpp -o my_program

UndefinedBehaviorSanitizer (UBSan)

UndefinedBehaviorSanitizer helps you find undefined behaviors in C++ code, like integer overflow or null pointer dereferences. Compile your code with:

g++ -fsanitize=undefined -g my_program.cpp -o my_program

ThreadSanitizer (TSan)

ThreadSanitizer detects data races in programs that use multithreading. You can enable TSan by compiling your program with:

g++ -fsanitize=thread -g my_program.cpp -o my_program

MemorySanitizer (MSan)

MemorySanitizer is used to detect uninitialized memory reads in C++ programs. To compile with MSan:

g++ -fsanitize=memory -g my_program.cpp -o my_program

To link against the sanitizers, make sure you have the appropriate libraries installed and linked, as some sanitizers might require additional options.


C++ sanitizers ASan UBSan TSan MSan memory errors undefined behavior thread safety debugging tools