Debug with GDB

Published:
2 minute read

First steps:

  1. Compile with proper flags: -g
  2. (Optional) Turn off code optimization: -O0

Debugging

  1. Run gdb with the program not passing its arguments in this step: gdb ./example
  2. After executing gdb, you can start the program with run command (with any needed arguments)
  3. You can run the gdb with the -tui flag to see the code while debugging.
CommandShortDescription
runrStart the executable from the start
listlList code lines where the execution is
quitqor Ctrl-D, gdb exits
Ctrl-C While running, hit Ctrl-C stops the execution and gdb shows where the program was
framefPrint the current line
backtracebaPrint the function call stack
continuecContinue execution
downdoGo to the called function
upupGo the calling function
info locals Print all local variables in the current scope
print varp varPrint variable’s value
display vardisp varPrint the variable’s value at every prompt
set varset varChange the variable’s value
watch varwa varStops if the variable’s value changes
break linebrInsert breakpoints into the code, you can pass filename or function name as well
deletedUnset a breakpoint
conditioncondBreaks if a condition is met
disabledisDisable a breakpoint
enableenEnable a breakpoint
info breakpointsinfo bList all breakpoints
tbreaktbTemporary breakpoint
nextnContinue until next line
stepsStep into function
finishfinContinue until the function’s end
untiluntContinue until line/function
helphPrint description of a command
info threads List all running/waiting threads from the process
thread id Switch execution to a specific thread id
br line thread id Set a breakpoint in a specific thread
thread apply 1 br line Set a breakpoint in line line of the thread 1
thread apply all bt Print the backtrace of all threads
  • Take a look at the GDB cheatsheet here.

Debugging MPI applications with GDB

If you have xserver running (use VCXSRV or Xming on windows for ssh), compile your code with -g and debug it with:

mpirun -np 2 xterm -e gdb <application>

More information at OpenMPI FAQ.

Inspecting the core file

If the program crashes with Segmentation fault message, it is sometimes helpful to increase the maximum core file size to save the in-memory state of the program at the time it crashes.

$ ./example
Segmentation fault
$ ulimit -c 2048
$ ./example
Segmentation fault (core dumped)
$ gdb ./example <corefile>