Skip to content
C++

GDB Quick Reference

GDB cheatsheet — breakpoints, watchpoints, stepping, inspecting variables, call stack, TUI mode, reverse debugging, and Python scripting.

Launch and Attach

bash
gdb ./myapp                    # load binary
gdb ./myapp core               # load with core dump
gdb -p 1234                    # attach to PID
gdb --args ./myapp arg1 arg2   # with arguments

# Inside GDB
(gdb) run arg1 arg2            # run with args
(gdb) run < input.txt          # redirect stdin
(gdb) start                    # run and stop at main()
(gdb) attach 1234              # attach to running process
(gdb) detach                   # detach
(gdb) quit                     # q

Breakpoints

break main                     # b main
break file.cpp:42              # b file.cpp:42
break MyClass::method          # break on method
break *0x4005f0                # break on address

info breakpoints               # i b — list all
delete 2                       # d 2 — delete #2
delete                         # delete all
disable 2                      # disable without deleting
enable 2

# Conditional breakpoints
break foo if x > 10
condition 2 x == 0             # add condition to existing

# Temporary — fires once, then auto-deleted
tbreak main

Watchpoints (Data Breakpoints)

watch x                        # break when x is written
rwatch x                       # break when x is read
awatch x                       # break on read or write

watch *(int*)0x601040          # watch memory address
watch -l expr                  # watch location (address)
info watchpoints

Stepping

next                           # n — step over (one source line)
step                           # s — step into
nexti                          # ni — step one machine instruction
stepi                          # si — step into machine instruction
finish                         # fin — run to end of current function
until 50                       # run until line 50
continue                       # c — resume execution
advance foo.cpp:100            # run until that line

Inspecting State

print x                        # p x — print variable
print *ptr                     # dereference pointer
print vec[0]                   # container element
print obj.field
print/x val                    # hex format
print/t val                    # binary
print/d val                    # decimal
print/f val                    # float
print/s ptr                    # as string

display x                      # auto-print x on every stop
info display
undisplay 1

x/10xw 0x7fff...               # examine: 10 hex words at address
x/20i $pc                      # disassemble 20 instructions at PC
x/s 0x4006b0                   # examine as string

Variables and Scope

info locals                    # all local variables
info args                      # function arguments
info variables name            # find variables by name
info registers                 # all CPU registers
info registers rax rbx         # specific registers
print $rax                     # register value
print $pc                      # program counter

Call Stack

backtrace                      # bt — full stack trace
backtrace 5                    # bt 5 — top 5 frames
backtrace full                 # with locals in each frame
frame 3                        # f 3 — select frame
up                             # go up one frame
down                           # go down one frame
info frame                     # details of current frame

Threads

info threads                   # list all threads
thread 3                       # switch to thread 3
thread apply all bt            # backtrace all threads
thread apply all info locals   # locals in all threads

# Thread-specific breakpoints
break foo thread 3

TUI Mode

bash
gdb -tui ./myapp               # start with TUI
# Inside GDB
layout src                     # source code layout
layout asm                     # assembly layout
layout split                   # source + assembly
layout regs                    # registers panel
Ctrl-x a                       # toggle TUI on/off
Ctrl-x 2                       # show/switch secondary window
Ctrl-L                         # refresh screen
focus cmd / src / asm / regs   # switch focus

Examining Memory

x/nfu addr                     # examine n units of format f, size u
# format: x=hex, d=decimal, u=unsigned, o=octal, t=binary, f=float, s=string, i=instruction
# size:   b=byte, h=halfword, w=word(4), g=giant(8)

x/4xg $rsp                     # 4 giant hex at stack pointer
x/8xb buf                      # 8 bytes at buf
x/32i main                     # disassemble 32 instructions from main

Signals

info signals                   # all signals and handling
handle SIGSEGV stop print      # stop on SIGSEGV
handle SIGUSR1 nostop noprint  # ignore SIGUSR1
signal SIGTERM                 # deliver signal to process

Catching Events

catch throw                    # stop on any exception thrown
catch catch                    # stop on any exception caught
catch syscall open             # stop on open() syscall
catch fork                     # stop on fork
catch exec                     # stop on exec
info catchpoints

Pretty Printers

bash
# gdb ships with std library pretty printers
# Enables for libstdc++ automatically

# In ~/.gdbinit
python
import sys
sys.path.insert(0, '/usr/share/gcc/python')
from libstdcxx.v6.printers import register_libstdcxx_printers
register_libstdcxx_printers(None)
end
p my_vector                    # prints: std::vector of length 3 = {1, 2, 3}
p my_map                       # prints map contents
p my_string                    # prints: "hello"

Reverse Debugging

record                         # start recording execution
reverse-continue               # rc — run backwards
reverse-next                   # rn — step backwards over
reverse-step                   # rs — step backwards into
reverse-finish                 # reverse out of current call

Scripting

# Run commands from file
gdb -x commands.gdb ./myapp

# commands.gdb
set pagination off
break main
run
bt
quit
python
# Python in GDB
python
val = gdb.parse_and_eval("my_variable")
print(f"value = {val}")

# Custom command
class PrintSizes(gdb.Command):
    def __init__(self):
        super().__init__("print-sizes", gdb.COMMAND_USER)
    def invoke(self, arg, from_tty):
        frame = gdb.selected_frame()
        for sym in frame.block():
            if sym.is_variable:
                print(f"{sym.name}: {gdb.parse_and_eval(sym.name).type.sizeof}")
PrintSizes()
end

.gdbinit Useful Settings

set print pretty on             # struct members on separate lines
set print array on              # array elements on separate lines
set print array-indexes on      # show [i] index
set pagination off              # no "---Type <return>---" prompt
set history save on             # save command history
set history size 10000
set confirm off                 # no confirmation prompts

# Useful aliases
define pv
  print *$arg0
end
Edit on GitHub