Skip to content
Tutorials Center
My learning

Topics

Lesson 118 of 171 ยท Errors and Debugging

Sanitizers and Valgrind

Find memory errors, undefined behavior, data races and leaks in C++ with AddressSanitizer, UBSan, ThreadSanitizer and Valgrind - flags, sample reports and how to read them.

The scariest C++ bugs do not crash where they happen. A write one element past the end of an array corrupts a neighbor, and the program fails an hour later in unrelated code. A signed overflow is undefined behavior, so the optimizer may remove a check you wrote. Two threads touch a counter without a lock and the result is right 999 times out of 1,000. A debugger shows you the crash site; it cannot show you the earlier mistake that caused it.

Sanitizers and Valgrind are tools that catch these mistakes at the moment they occur. Sanitizers are built into GCC and Clang: you add a compiler flag, and the compiler inserts checks into your program. Valgrind needs no recompilation: it runs your finished binary on a virtual CPU that tracks every memory access. In this lesson you will learn what each tool finds, which flags to use, how to read a report, and how to make them part of your routine. The sanitizer programs themselves are shown as read-only code, since they need compiler flags that the in-browser runner does not pass. The runnable examples show the safe counterparts and a leak counter you can write yourself.

The family of tools

Tool Flag Finds Typical slowdown
AddressSanitizer (ASan) -fsanitize=address buffer overflows, use-after-free, use-after-scope, double free, (on Linux) leaks about 2x
UndefinedBehaviorSanitizer (UBSan) -fsanitize=undefined signed overflow, bad shifts, null dereference, misaligned access, invalid casts small
ThreadSanitizer (TSan) -fsanitize=thread data races, some deadlock patterns 5 to 15x
MemorySanitizer (MSan, Clang only) -fsanitize=memory reads of uninitialized memory about 3x
Valgrind Memcheck valgrind ./program invalid reads/writes, leaks, uninitialized values 20 to 50x

ASan and UBSan can be combined (-fsanitize=address,undefined). TSan cannot be combined with ASan, and MSan stands alone, so you build separate test binaries for them.

flowchart LR
    S["source code"] --> C["compiler<br/>-fsanitize=..."]
    C --> B["instrumented binary"]
    B --> R["run tests / program"]
    R -->|"bug happens"| E["report with<br/>stack traces"]
    R -->|"no bug"| OK["normal exit"]

A sanitizer adds checks at compile time and reports errors with stack traces while the program runs.

Compile with debug information and without heavy optimization, so reports show real line numbers and variable names:

Terminal
g++ -std=c++23 -g -O1 -fno-omit-frame-pointer \
    -fsanitize=address,undefined main.cpp -o main
./main

-fno-omit-frame-pointer keeps stack traces accurate. In CMake, a common pattern is an option that adds the flags to both the compile and link steps; see build systems and compiler flags. Run your whole test suite under sanitizers in continuous integration. They only find bugs on code paths that actually execute, so good tests are what make them effective.

AddressSanitizer: memory errors

ASan replaces malloc and new with versions that surround each block with poisoned "red zones" and tracks freed memory. Any access to a red zone or to freed memory is reported at once.

A classic overflow, read-only:

C++
#include <vector>

int main() {
    std::vector<int> v(3, 1);
    return v[3];          // one past the end: reads heap memory that is not ours
}

With -fsanitize=address, the program stops with a report like this (addresses and numbers vary):

TEXT
==12345==ERROR: AddressSanitizer: heap-buffer-overflow on address 0x602000000020 ...
READ of size 4 at 0x602000000020 thread T0
    #0 0x... in main main.cpp:5
0x602000000020 is located 0 bytes after 12-byte region [0x602000000010,0x60200000001c)
allocated by thread T0 here:
    #0 0x... in operator new(unsigned long)
    #1 0x... in std::vector<int>::vector(...)

How to read it: the first line names the bug class (heap-buffer-overflow), the next gives the access (a read of 4 bytes) and the stack trace of the faulty line, and the section after it explains where the address lies: 0 bytes after a 12-byte block that was allocated by the vector. The other common ASan classes are heap-use-after-free, stack-buffer-overflow, stack-use-after-scope (a pointer to a dead local), global-buffer-overflow and attempting double-free.

The safest fix for out-of-range indexing is to make the check explicit where a mistake is plausible. The at member function checks the index and throws a catchable exception:

C++ at() turns silent corruption into an exception

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with std::cin or std::getline), it gets the next line from this box.

Checked access is good for bugs you want to handle. A sanitizer is for bugs that should simply never exist: it finds them during testing, and you remove them from the code.

Use-after-free and dangling references

C++
#include <string>
#include <string_view>

std::string_view first_word() {
    std::string text = "hello world";
    return std::string_view(text).substr(0, 5);   // refers to text, which is destroyed
}

int main() {
    std::string_view w = first_word();
    return w.size() > 0 ? w[0] : 0;               // ASan: stack-use-after-return
}

ASan can detect this one only with ASAN_OPTIONS=detect_stack_use_after_return=1 on some GCC versions, so remember that default settings do not find everything. The cure is design, not tools: return std::string by value, or keep the owner alive (see string_view and references).

Leaks and RAII

On Linux, ASan includes LeakSanitizer: at exit it lists memory that was allocated but never freed and no longer reachable. A leak found at exit is usually a missing delete, or an owner that was never destroyed. The best fix is to avoid manual ownership entirely. You can see the principle without any tool by counting allocations yourself. Replacing the global operator new and operator delete lets a program count every allocation made through new:

C++ A hand-made leak counter

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with std::cin or std::getline), it gets the next line from this box.

The count rises to 1 for the leaked Widget and stays there until the delete. The unique_ptr version adds nothing to it: its Widget is freed when the scope ends, so the count stays at 1 (the leak) and finally returns to 0. Real leak detectors do the same bookkeeping with much better reporting: they record a stack trace for each allocation, so the report tells you where the leaked memory was created. See unique_ptr and RAII for how to prevent leaks by construction.

UndefinedBehaviorSanitizer

UBSan checks for operations the standard leaves undefined, and prints a short message when one happens, without necessarily stopping:

C++
#include <climits>
#include <print>

int main() {
    int x = INT_MAX;
    int y = x + 1;                 // signed overflow
    int shift = 40;
    int z = 1 << shift;            // shift count too large for int
    std::println("{} {}", y, z);
}
TEXT
main.cpp:6:15: runtime error: signed integer overflow: 2147483647 + 1 cannot be represented in type 'int'
main.cpp:8:15: runtime error: shift exponent 40 is too large for 32-bit type 'int'

By default UBSan prints and continues. Add -fno-sanitize-recover=undefined to stop at the first problem, which is better in tests. Other checks include null pointer use, misaligned pointers, out-of-bounds array indexing on fixed-size arrays, and invalid enum or bool values. If overflow is part of your design, use unsigned arithmetic, which wraps by definition, or check before you add:

C++ Detecting overflow before it happens

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with std::cin or std::getline), it gets the next line from this box.

ThreadSanitizer: data races

A data race happens when two threads access the same memory without synchronization and at least one writes. It is undefined behavior even if the program "seems to work". TSan finds races by tracking, for each memory location, which thread touched it and what synchronization happened in between. Build with -fsanitize=thread (and -g, -O1) and run:

C++
#include <thread>

int counter = 0;

int main() {
    std::thread a([] { for (int i = 0; i < 100000; ++i) ++counter; });
    std::thread b([] { for (int i = 0; i < 100000; ++i) ++counter; });
    a.join();
    b.join();
}
TEXT
WARNING: ThreadSanitizer: data race (pid=12345)
  Write of size 4 at 0x... by thread T2:
    #0 operator() main.cpp:6
  Previous write of size 4 at 0x... by thread T1:
    #0 operator() main.cpp:5

The fix is to protect the shared variable with a mutex or make it atomic. This version has no race and always prints the same result:

C++ The race fixed with an atomic

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with std::cin or std::getline), it gets the next line from this box.

TSan can only report races that happen during the run, so run multi-threaded tests under it often, and with several repetitions.

Valgrind

Valgrind's Memcheck tool needs no special build; compile with -g so it can show line numbers, then run:

Terminal
g++ -std=c++23 -g -O0 main.cpp -o main
valgrind --leak-check=full --show-leak-kinds=all ./main

It reports invalid reads and writes, use of uninitialized values (Conditional jump or move depends on uninitialised value(s)), mismatched new[]/delete, and a leak summary with categories: definitely lost (real leaks), indirectly lost (reachable only through a leaked block), possibly lost and still reachable (memory held at exit, often harmless). Focus on "definitely lost" first.

Choose between the tools like this:

  • Sanitizers are faster and give better messages for stack and global overflows, but they require recompiling.
  • Valgrind works on any binary and finds uninitialized reads without Clang's MSan, but it is slow and misses stack-array overflows.
  • Do not run Valgrind and ASan on the same binary; ASan's own allocator conflicts with Valgrind.

Sanitizers and Valgrind support Linux and macOS best. On Windows, MSVC offers /fsanitize=address, and Dr. Memory or Visual Studio's diagnostics fill the same role. An exit code or message from the tool is a bug report with a stack trace: treat it as a failing test.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. Which flag enables AddressSanitizer?

    -fsanitize=address adds the memory checks. -fsanitize=thread is ThreadSanitizer, and -Wall only enables compiler warnings, not run-time checks.
  2. 2. You want to detect a data race between two threads. Which tool do you use?

    ThreadSanitizer tracks synchronization between threads and reports unsynchronized conflicting accesses. It cannot be combined with ASan in the same build.
  3. 3. Why should sanitizer builds use -g and low optimization such as -O1?

    Debug information lets the report name source lines, and light optimization avoids code being merged or inlined beyond recognition while keeping the program reasonably fast.
  4. 4. A sanitizer reports nothing for your test run. What can you conclude?

    Sanitizers only observe what actually happens during a run. Bugs on paths your tests never take stay hidden, so combine them with good test coverage.
  5. 5. Which is true about Valgrind compared with ASan?

    Valgrind interprets the compiled program on a virtual CPU, so it needs no special build, at the cost of a 20 to 50 times slowdown. It should not be run together with ASan.

Summary

  • Sanitizers insert run-time checks at compile time; Valgrind checks an unmodified binary at much lower speed.
  • Use -fsanitize=address,undefined for memory errors and undefined behavior, and a separate build with -fsanitize=thread for data races.
  • Build with -g -O1 -fno-omit-frame-pointer so reports contain useful stack traces.
  • A report names the bug class, the faulty access with a stack trace, and where the memory was allocated.
  • A clean run only proves the executed paths are clean, so run your tests under sanitizers regularly.
  • The best fixes are structural: RAII and smart pointers, owning types instead of dangling views, locks or atomics for shared state.

Next: Unit Testing with GoogleTest and Catch2, the safety net that gives sanitizers and debuggers something to run.