How do I use sanitizers in debug builds?

Using sanitizers in debug builds can help catch bugs, memory issues, and undefined behavior during development. In C++, you can enable these sanitizers when compiling your code with tools such as Clang or GCC. Here's how to configure your development environment to use AddressSanitizer, UndefinedBehaviorSanitizer, and ThreadSanitizer in debug builds.

Example Configuration

# For Clang
# Compile with AddressSanitizer
clang++ -g -fsanitize=address -o my_program my_program.cpp

# Compile with UndefinedBehaviorSanitizer
clang++ -g -fsanitize=undefined -o my_program my_program.cpp

# Compile with ThreadSanitizer
clang++ -g -fsanitize=thread -o my_program my_program.cpp

To enable sanitizers with GCC, you can use similar flags:

# For GCC
# Compile with AddressSanitizer
g++ -g -fsanitize=address -o my_program my_program.cpp

# Compile with UndefinedBehaviorSanitizer
g++ -g -fsanitize=undefined -o my_program my_program.cpp

# Compile with ThreadSanitizer
g++ -g -fsanitize=thread -o my_program my_program.cpp

Run your program normally from the command line, and if any issues are detected, the sanitizer will report them in the output.


C++ sanitizers debug builds AddressSanitizer UndefinedBehaviorSanitizer ThreadSanitizer