How do I enable sanitizers with GCC?

To enable sanitizers in GCC (GNU Compiler Collection), you can use the -fsanitize flag followed by the type of sanitizer you wish to enable. Common sanitizers include address sanitizer (address), undefined behavior sanitizer (undefined), and memory sanitizer (memory).

For example, if you want to enable address sanitizer, you would compile your C++ code like this:

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

After compiling, running the program with sanitizers enabled will help you catch various types of runtime errors and undefined behaviors.


sanitizers GCC address sanitizer undefined behavior sanitizer memory sanitizer C++ debugging compiling with sanitizers