Learn C
#include "advanced/debugging.h"

Debugging with GDB & Sanitizers in C

#concept

Debug builds compile with -g (symbols) and -O0 (no reordering) so GDB 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 over, step into), continue.

Sanitizers find what debuggers can't see: -fsanitize=address catches overflows, use-after-free, and leaks; -fsanitize=undefined catches signed overflow and misaligned access. Run test suites under both regularly — silent corruption becomes loud, located errors.

#how it works
1

Build debuggable

gcc -g -O0 app.c — symbols for names/lines, no optimization moving code 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 — overflows, use-after-free, leaks.

4

UBSan for undefined behavior

-fsanitize=undefined flags signed overflow and misaligned access — bugs that otherwise behave impossibly.

#example
$ gcc -g -O0 app.c -o app
$ gdb ./app
(gdb) break main
(gdb) run
(gdb) print x
$ gcc -fsanitize=address app.c && ./a.out
Output
Breakpoint 1 at main
[Inferior started]
$1 = 42
ERROR: heap-buffer-overflow on address ...
1The debug build plus break main stops at the first line, ready for inspection.
2print x evaluates live state ($1 = 42) — no guessing about values.
3The sanitizer build instead reports memory violations automatically with addresses and traces.
#use cases
Localizing segfaults to exact lines with backtraces
Watching variables evolve across loop iterations
Catching heap corruption in CI with sanitizer runs
Proving UB 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.