debugging · medium
Debugging: GDB — Crash Diagnosis, Breakpoints, Watchpoints, Core Dumps
GDB workflow: compile with -g -O0 (debug symbols, no optimizations). Run under GDB or load a core dump (ulimit -c unlimited before crash). On crash: bt → backtrace; frame N → select frame; info locals/args → see variables; print expr → evaluate. Breakpoints: break file:line; condition N expr → conditional. Watchpoints: watch var → break on write; rwatch → break on read. Threads: info threads; thread N; thread apply all bt → dump all backtraces (deadlock diagnosis). Scripts: .gdbinit for automated setup; Python API for custom pretty-printers. Production: compile prod with -g -O2 (stripped separately); ulimit -c unlimited; post-mortem with core dumps. Key insight: the bt → frame → print loop is the core debugging rhythm for any crash.
GDB essentials: compile -g -O0; bt (crash location); frame N + info locals (inspect state); break file:N + condition; watch var (break on change); thread apply all bt (deadlock); gdb ./app core for post-mortem — no reproduction needed.
The code
# Compile with debug infog++ -g -O0 -fsanitize=address myapp.cpp -o myapp# -g: DWARF debug info -O0: no optimizations
# Start GDBgdb ./myapp
# Core dump analysisgdb ./myapp coreulimit -c unlimited # enable core dumps first
# Essential GDB commands (muscle memory for interviews)run [args] # start the programbt # backtrace — where did we crash?frame N # switch to stack frame Ninfo locals # all local vars in current frameinfo args # function argumentsprint var # print variable / expressionx/10wx 0xaddr # examine 10 words at addressbreak file.cpp:42 # breakpoint at linebreak Class::method # breakpoint at methodcondition 1 x > 5 # conditional breakpointwatch var # watchpoint: break on writerwatch var # break on readstep # step into (s)next # step over (n)continue # continue (c)finish # run until function returnsset var = value # change a variable livethread apply all bt # all threads' backtraceinfo threads # list threadsdisassemble # view assemblyWhat this lesson walks through
- 01GDB workflow — compile with -g, then debug
- 02Segfault — bt shows the crash location instantly
- 03Breakpoint + conditional — stop only when interesting
- 04Thread debugging — all-thread backtrace
- 05GDB scripting — .gdbinit and Python automation
- 06Core dump analysis — post-mortem without a running process
The GDB workflow starts with compilation: g++ -g -O0 gives debug symbols (DWARF) and disables optimizations so variables are visible and stack frames are accurate. Then either run the program under GDB, or load a core dump. Core dumps require ulimit -c unlimited before the crash.
See it animated — step by step, at your own pace
Unlock the full interactive walkthrough of Debugging: GDB — Crash Diagnosis, Breakpoints, Watchpoints, Core Dumps and 100+ animated C++ interview lessons.