An Introduction to GDB

An Introduction to GDB


GDB is the GNU Debugger. For more information, see the man pages or the on-line GDB documentation. Sadly, help from within gdb is difficult to navigate.

Here is a quick way to get started:

Running gdb
Make sure your executable is compiled with the -g option. Type in
gdb programname
or
gdb programname core 
The latter will allow you to examine the coredump as if the program was running and had just faulted.

Running your program in gdb
Once gdb is up, simply type "run" or "r" to start your program. If your program takes command line arguments, simply add them after the run command.

Detecting segfaults
No brainer - once your code starts running and if a segfault occurs, the debugger alerts you and gives you a debugger prompt. Type in bt (the "backtrace" command). This prints out the current stack and you can immediately see where the segfault occurred.

Breakpoints
Breakpoints are places in code that you specify. Whenever the computer reaches a breakpoint, it pauses and gives you the debugger prompt just before it executes the line.

Set a breakpoint by the b command ("break"). You can do the following :

break fileA.c:main
which places a breakpoint in the main function in fileA.c
break fileA.c:125
which places a breakpoint at line 125 of fileB.c

Typing "d 1" deletes breakpoint 1. Typing "disable 1" disables breakpoint 1. You can enable this breakpoint again by typing "enable 1".

Examining Data
Once you've gotten to where you want to start looking at variables, you can do the following:
print a
prints out the value of variable a, assuming a is valid in the current scope.
print (char) a
casts a to a char before printing it out.
print f(123)
execute any function f with arguments 123, and print its return value. This can have side effects.
x 0xfaf47
print out the contents of a given memory address.
display x
print out the value of x whenever the program is stopped.

Tracing
Step through a program using the step (execute line by line, entering any function calls) and next (execute line by line, skipping over function calls).

continue resumes normal execution of the program until a breakpoint is hit.

finish resumes normal execution of the program until the end of this procedure or a breakpoint is hit (which ever comes first).

Quitting
Type "quit".

This is by no means a complete listing, but it's what you'll use most of the time.

Other Tips

Supports emacs-like editing of command line (ctrl-a, -e, -f, -b, -d will move you around the line. ctrl-p, -n will move you through the history of previous commands, just like in tcsh).


Original by bershad@cs.washington.edu.
Modified by wolman@cs.washington.edu, Autumn 1997.