How do I use sanitizers to find undefined behavior in C++?

Using sanitizers in C++ is an effective way to detect undefined behavior, memory leaks, and other programming errors in your code. Sanitizers are tools integrated into the compiler that can help identify issues during runtime. Below is a guide on how to use sanitizers in C++ to find undefined behavior.

What are Sanitizers?

Sanitizers are a suite of tools that help catch errors in C++ programs. Two commonly used sanitizers are:

  • AddressSanitizer (ASan): Detects memory-related errors such as buffer overflows and use-after-free errors.
  • UndefinedBehaviorSanitizer (UBSan): Catches undefined behavior in C++ programs.

How to Use Sanitizers

To enable sanitizers, you need to compile your C++ program with specific flags. For example:

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

Here, -fsanitize=undefined enables the UndefinedBehaviorSanitizer, and -g includes debugging information for better error reporting.

Example Code

Here is an example that demonstrates how to catch undefined behavior using UBSan:

#include <iostream> int main() { int x = 5; int y = x / 0; // Division by zero std::cout << "Value of y: " << y << std::endl; return 0; }

When you run this program with UBSan enabled, it will produce an error message indicating the division by zero, allowing you to identify and fix the issue.


C++ sanitizers undefined behavior AddressSanitizer UndefinedBehaviorSanitizer debugging programming errors