Learn C++
#include "tooling/debugging.hpp"

Debugging with GDB & Sanitizers in C++

//concept

Always compile debug builds with -g (symbols) and no optimization (-O0) when hunting bugs — GDB then maps crashes to source lines, prints variables, and steps execution. The core loop is tiny: break on a line, run, inspect (print x, backtrace), step (next steps over, step steps in), continue.

Sanitizers find what debuggers can't see: -fsanitize=address catches overflows, use-after-free, and leaks at run time, while -fsanitize=undefined catches signed overflow, misaligned access, and other UB. Run your test suite under both regularly — they turn silent corruption into loud, located errors.

//how it works
1

Build debuggable

g++ -g -O0 app.cpp — symbols for names/lines, no optimization reordering your code out from under the debugger.

2

Break, run, inspect

break main, run, print x, backtrace, next/step, continue — six GDB commands covering nearly every session.

3

AddressSanitizer for memory

-fsanitize=address aborts on the exact overflowing line with a full report — heap overflows, use-after-free, double-free, leaks.

4

UBSan for undefined behavior

-fsanitize=undefined flags signed overflow, null-plus-offset, and misaligned access — bugs that otherwise manifest as impossible behavior.

//example
$ g++ -g -O0 app.cpp -o app
$ gdb ./app
(gdb) break main
(gdb) run
(gdb) print x
$ g++ -fsanitize=address app.cpp && ./a.out
Output
Breakpoint 1 at main
[Inferior started]
$1 = 42
ERROR: heap-buffer-overflow on address ...
1The debug build plus break main stops execution at the first line, ready for inspection.
2print x evaluates the variable in context ($1 = 42) — live state, no guessing.
3The sanitizer build instead reports memory violations automatically, with addresses and stack traces.
//use cases
Localizing segfaults to exact lines with backtraces
Watching variables evolve across loop iterations
Catching heap corruption in CI with AddressSanitizer runs
Proving undefined behavior absent with UBSan before release

Recommended resourcesAffiliate links · may earn us a commission

Recommended for learners

Structured coding coursesVideo courses that pair well with visual practice — pick one language and go deep.Browse courses Pro code editor & AI assistantWrite, debug and explain code faster while you practice the patterns here.Try it free Classic DSA interview booksThe reference books interviewers themselves learned from — great next to the visualizers.See the books

Practice what you learned

Re-implement each visualized algorithm in C++ yourself — building beats watching.