Debugging with GDB & Sanitizers in C++
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.
Build debuggable
g++ -g -O0 app.cpp — symbols for names/lines, no optimization reordering your code out from under the debugger.
Break, run, inspect
break main, run, print x, backtrace, next/step, continue — six GDB commands covering nearly every session.
AddressSanitizer for memory
-fsanitize=address aborts on the exact overflowing line with a full report — heap overflows, use-after-free, double-free, leaks.
UBSan for undefined behavior
-fsanitize=undefined flags signed overflow, null-plus-offset, and misaligned access — bugs that otherwise manifest as impossible behavior.
$ g++ -g -O0 app.cpp -o app$ gdb ./app(gdb) break main(gdb) run(gdb) print x$ g++ -fsanitize=address app.cpp && ./a.outRecommended resourcesAffiliate links · may earn us a commission
Recommended for learners
Practice what you learned
Re-implement each visualized algorithm in C++ yourself — building beats watching.