GNU Debugger

GNU Project Debugger (GDB)

GDB allows you to see what is going on ‘inside’ another program while it executes.

Super useful for debugging in C and C++!

GDB on M1 Mac

Unfortunately, it seems that I cannot use gdb yet on my M1 Mac, it’s not supported on the Macbook’s arm64 architecture. Instead, I use lldb.

When you compile, make sure to use the -g flag

Resources

Commands

This is the high level commands.

// compile program
g++ -g test.cc -o test
 
// enter gdb terminal
gdb ./a.out
 
// ALTERNATIVE: feed it the executable
file test
 
// start a breakpoint
break line-number
break fn-name 
 
// run program on input
run < 1.in
 
// enter the more readable interface
layout src

Commands that I use a lot

  • next: runs one line of the program n
  • print variable: allows you to see value of that variable at that time p
  • display var: prints the value of var after each next/step
  • continue: runs the program until the next breakpoint c
  • refresh: fix the layout src display

More Commands

  • watch var: breaks the program whenever var is changed
  • step: runs one instruction of the program
  • list: show surrounding lines of the program
  • backtrace: lists the sequence of function calls that got you to your current location
  • up/down: change the function in the call stack we are observing so as to inspect other variables
  • set var: allows us to set a variable at runtime
  • undipslay 1 : stops displaying first var set with display
  • delete breakpoint number: rename break point from use (watch and break)