Debugging with GDB
Debugging with GDB

Debuggers

Debuggers

  • Step through code one line at a time
  • Inspect variables, including structs and classes
  • View disassembly
  • Check the call stack
  • gdb - Command-line debugger
  • kdbg - GUI frontend for gdb

gdb

Using gdb

  • gdb PROGRAM launches the debugger for debugging PROGRAM
  • Note: You will want to pass g++ the -g flag when you compile!
  • run arg1 arg2 runs the command with command line arguments arg1 and arg2
  • backtrace or bt shows the call stack

An Example Run

# Compile stuff first
$ make
g++ -c -g -Wall --pedantic-errors -s main.cpp
g++ main.o -o program

# Give it to GDB
$ gdb program
GNU gdb (Ubuntu 7.7.1-0ubuntu5~14.04.2) 7.7.1
Copyright (C) 2014 Free Software Foundation, Inc.
...
Reading symbols from program...done.
(gdb) run
Starting program: /home/user/demo/hello-world/program
Hello world!
[Inferior 1 (process 14646) exited normally]
(gdb) quit

Setting breakpoints with gdb

  • break main.cpp:10 will stop execution whenever line 10 in main.cpp is reached.
  • continue resumes running as normal.
  • step runs one more line of code; steps into functions as necessary.
  • next runs until execution is on the next line; steps over functions.
  • finish runs until the current function returns.
  • delete removes all breakpoints.
  • More on breakpoints

Looking at variables with gdb

  • print VARIABLE prints the contents of variable with name VARIABLE
    • p VARIABLE also works
    • p also works with expressions of just about any sort
  • x address examines one word memory at a given address
  • x/2 address examines two words of memory
  • info registers lists all CPU register values
  • p $REGNAME prints the value of a CPU register

Miscellaneous

  • Conditional Breakpoints: condition BPNUMBER EXPRESSION
  • Editing variables at runtime with gdb:
    • set var VARIABLE = VALUE assigns VALUE to VARIABLE
    • set {int}0x1234 = 4 writes 4 (as an integer) to the memory address 0x1234
  • Disassembling code: disassemble FUNCTION prints the assembly for a function named FUNCTION