C Reference ยท Concepts and Tools
Debugging C with gdb
A practical gdb reference for C: compile with -g, set breakpoints, step, print variables, read a backtrace, use watchpoints and debug a crash or a core dump.
gdb, the GNU debugger, lets you stop a running C program, look at its variables and call stack, and execute it one line at a time. Instead of adding printf calls and recompiling, you ask the program questions while it runs. Clang users have the equivalent lldb with similar commands, and Visual Studio and VS Code provide graphical front ends for both.
A debugger needs an interactive terminal, so the gdb sessions on this page are read-only. The programs themselves are runnable, so you can see the bug first and then follow the session on your own machine.
Prepare the program
Compile with debug information and without optimization. Optimized code reorders lines and removes variables, which makes stepping confusing.
gcc -std=c23 -g -O0 -Wall -Wextra program.c -o program gdb ./program
A buggy program
The function should add all count numbers, but the output is too small. Run it to see the symptom, then use gdb to find the cause.
Press Run (or Ctrl + Enter) to see the result here.
Program input ยท what you'd type while the program runs
Type the answers before you press Run, one per line. Each time the program reads a line (with scanf or fgets), it gets the next line from this box.
A typical session (read-only; (gdb) is the prompt, and output is abbreviated):
(gdb) break sum
Breakpoint 1 at ...: file program.c, line 4.
(gdb) run
Breakpoint 1, sum (values=0x7ffe..., count=4) at program.c:4
4 int total = 0;
(gdb) next
5 for (int i = 0; i < count - 1; i++) {
(gdb) next
6 total += values[i];
(gdb) print i
$1 = 0
(gdb) print values[0]@4
$2 = {10, 20, 30, 40}
(gdb) display total
1: total = 0
(gdb) until 8
...
(gdb) finish
Run till exit from #0 sum (...)
Value returned is $3 = 60
Stepping with next while display total is active shows 10, 30, 60 and then the loop ends (finish reports the same 60): the condition i < count - 1 skips the last element. The fix is i < count.
Commands you will use most
| Command | Short | What it does |
|---|---|---|
run [args] |
r |
start the program (with arguments) |
break function / break file.c:20 |
b |
stop at a function or line |
tbreak |
a breakpoint that is deleted after it hits once | |
info breakpoints |
i b |
list breakpoints |
delete N / disable N |
d |
remove or switch off breakpoint N |
continue |
c |
run until the next breakpoint |
next |
n |
execute one line, stepping over calls |
step |
s |
execute one line, stepping into calls |
finish |
run until the current function returns, and print its value | |
until |
run until a later line (finishes a loop) | |
print expr |
p |
evaluate and show an expression: p total, p *ptr, p arr[1]@3, p/x n |
display expr |
show an expression after every stop | |
x/8xb &var |
examine raw memory: count, format (x, d, s, i), unit size |
|
backtrace |
bt |
print the call stack |
frame N / up / down |
f |
move between stack frames, then info locals and info args |
watch var |
stop whenever var changes |
|
break ... if cond |
conditional breakpoint: break 6 if i == 3 |
|
set var x = 5 |
change a variable while stopped | |
list |
l |
show source around the current line |
quit |
q |
leave gdb |
Debugging a crash
When a program dies with a segmentation fault, run it under gdb. It stops at the faulting line and backtrace shows how the program got there.
Press Run (or Ctrl + Enter) to see the result here.
Program input ยท what you'd type while the program runs
Type the answers before you press Run, one per line. Each time the program reads a line (with scanf or fgets), it gets the next line from this box.
The macro above is poor man's backtrace: it prints the path through the functions. In gdb you get the same information for free, with arguments:
(gdb) run Program received signal SIGSEGV, Segmentation fault. 0x... in copy_name (dst=0x0, src=0x...) at program.c:12 12 dst[0] = src[0]; (gdb) bt #0 copy_name (dst=0x0, src=0x...) at program.c:12 #1 0x... in main () at program.c:25 (gdb) frame 1 (gdb) info locals
Frame 0 is where the program stopped; dst=0x0 shows a null pointer was passed in, so the bug is in main, one frame up.
Core dumps
If a crash happened elsewhere, enable core files (ulimit -c unlimited), run the program until it crashes, and open the dump later: gdb ./program core. Then use bt, frame and info locals as usual. This works only if the executable matches the build that crashed.
Usage notes
- Use
-gand-O0while debugging. At-O2you may see<optimized out>for variables, and stepping jumps around.-Ogis a compromise. - Debug a running process with
gdb -p PID(you may need permission), and pass program arguments withgdb --args ./program one two. - Reverse and record:
recordthenreverse-steplets you step backwards on supported systems;rris a stronger record-and-replay tool. - Watchpoints are slow unless the hardware supports them, but they find the line that corrupts a variable.
- Scripts: put commands in a file and run
gdb -x commands.gdb ./program, orgdb -batch -ex run -ex bt ./programfor non-interactive runs in CI. - Front ends:
gdb -tuishows source and prompt together; VS Code, CLion and Emacs use gdb or lldb under the hood. - Combine tools. Memory bugs are easier to find with Sanitizers or Valgrind; gdb is for understanding logic and inspecting state.
Related
- Compilers for the
-gand-Oflags - Sanitizers, Valgrind and assert
- Tutorial: Debugging