C Basics · intermediate · ~20 min

Debugging with gdb

Step through a program, inspect variables, read backtraces.

Overview

gdb is the microscope for C. Twelve commands cover almost every debugging session: start, run, break, next, step, finish, continue, print, info locals, backtrace, x/16xb, quit.

Why it matters

When printf debugging stops working you reach for gdb. Every C developer who works past 6 months either learns gdb or stays stuck on intermittent bugs forever.

Core concepts

Breakpoints. break main, break file.c:42, break function_name.

Stepping. next = step over a call; step = step into.

Inspection. print x, print *p, info locals, info registers, bt for the call stack.

Memory dump. x/16xb addr prints 16 bytes in hex.

Watchpoints. watch x stops every time x changes — perfect for 'who is corrupting this variable?'.

Pentester mindset. Reverse-engineering uses the same gdb commands plus disas and info registers. The boundary between debugging and RE is fuzzy.

Syntax notes

See notes/gdb-cheatsheet.md in the c-pentest-learning folder for a single-page reference.

Lesson

GDB is the GNU debugger. It lets you pause execution, print any variable, dump memory in hex, and walk the stack. Compile with -O0 -g so symbols are full and locals stay in scope.

Code examples

gcc -O0 -g -Wall prog.c -o prog
gdb ./prog
(gdb) break main
(gdb) run
(gdb) print x
(gdb) next
(gdb) bt

Line by line

(gdb) break factorial      # break inside the function
(gdb) run                  # start the program
...stops at factorial...
(gdb) info locals          # see n
(gdb) print n
(gdb) finish               # run until return; print return value
(gdb) bt                   # call stack — confirms who called us

Common mistakes

  • Compiling with -O2 and being confused why info locals is empty.

Debugging tips

For a segfault, gdb stops at the offending line; bt shows you how you got there.

Memory safety

gdb itself doesn't fix memory bugs — but it lets you observe them. For an actual diagnostic, build with -fsanitize=address (see sanitizers lesson).

Real-world uses

Investigating any C-language CVE write-up; reverse-engineering a binary; debugging a kernel panic post-mortem with gdb vmlinux core.

Practice tasks

  1. Break on main, step through, print every local. 2. Set a watchpoint on a variable that gets corrupted by an out-of-bounds write. 3. Read a backtrace from a segfault and identify the bug.

Summary

Twelve commands; compile with -O0 -g; the microscope of C.