How do I use Address/Leak/Thread/Undefined sanitizers with GCC?

Using AddressSanitizer, LeakSanitizer, ThreadSanitizer, and UndefinedBehaviorSanitizer with GCC can help identify various types of coding errors, memory leaks, and concurrency issues in your C++ applications. Below are the steps to enable and use these sanitizers effectively.

Enabling AddressSanitizer

To compile your C++ code with AddressSanitizer, you can use the following flags:

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

Using LeakSanitizer

LeakSanitizer is integrated with AddressSanitizer. By using AddressSanitizer, you'll automatically detect memory leaks. Compile your code as shown above and run it:

./my_program

Enabling ThreadSanitizer

To check for data races and threading issues, use ThreadSanitizer with the following command:

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

Using UndefinedBehaviorSanitizer

To find undefined behavior issues, compile your code with the following command:

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

Running the Sanitized Program

Run your compiled program as you normally would. The sanitizers will report any issues detected:

./my_program

C++ GCC AddressSanitizer LeakSanitizer ThreadSanitizer UndefinedBehaviorSanitizer