GDB Command Reference

A simple guide to the GNU Debugger.

Download GDB

Getting Started

1. Compile with Debug Symbols:

gcc -g -o myprogram main.c

2. Start GDB:

gdb ./myprogram

3. Run with Arguments:

gdb --args ./myprogram arg1 arg2

Command Reference

Execution Control

Command Shortcut Description
run r Start program execution.
continue c Continue execution until next breakpoint.
next n Step over function calls.
step s Step into function calls.
finish fin Run until the current function returns.
until u Run until a line greater than the current one is reached (loop exit).
kill k Kill the program being debugged.
quit q Exit GDB.

Breakpoints & Watchpoints

Command Shortcut Description
break [location] b Set a breakpoint. E.g., b main, b 15, b file.c:20.
watch [expr] Stop when value of [expr] changes (Hardware Watchpoint).
rwatch [expr] Stop when [expr] is read.
awatch [expr] Stop when [expr] is read or written.
info break i b List all breakpoints and watchpoints.
delete [n] d [n] Delete breakpoint [n]. Delete all if [n] is omitted.
clear [location] Clear breakpoints at specific location.
disable/enable [n] Disable or enable breakpoint [n] without deleting it.

Inspection & Variables

Command Shortcut Description
print [expr] p Print value of expression or variable.
x/[fmt] [addr] Examine memory. E.g., x/10x &array (10 hex integers).
display [expr] Automatically print [expr] every time the program stops.
undisplay [n] Stop displaying item [n].
info locals Show local variables in current stack frame.
info variables List all global and static variable names.
ptype [name] Show type definition of a variable/struct.

Stack & Threads

Command Shortcut Description
backtrace bt Print the call stack (where you came from).
frame [n] f Select stack frame [n].
up / down Move selection up or down the call stack.
info threads List all threads.
thread [n] Switch to thread [n].
thread apply all bt Print backtrace for all threads.

Source & Layout

Command Shortcut Description
list l Show source code around current line.
disassemble disas Show assembly code for current function.
layout src Enable TUI mode showing source code window.
layout asm Enable TUI mode showing assembly window.
layout split Show both source and assembly in TUI.
ctrl+x a Toggle TUI mode on/off.

Debugging Core Files

If your program crashes (segmentation fault), you can debug the state it was in using a core dump.

Enable Core Dumps: Run ulimit -c unlimited in your terminal before running the program.

Usage

gdb <executable> <core_file>

Example Session

$ ulimit -c unlimited
$ ./crashing_program
Segmentation fault (core dumped)
$ gdb ./crashing_program core
...
(gdb) bt
#0  0x0000000000401136 in perform_crash () at main.c:5
#1  0x000000000040114b in main () at main.c:10