GDB Tutorial

A debugger is a program that runs other programs, allowing the user to exercise control over these programs, and to examine variables when problems arise. The most popular debugger for UNIX systems is GDB, the GNU debugger. GDB has tons of features, however, you only need to use a few for it to be very helpful.

Also, this reference card is useful when first learning the gdb commands.

Basic features of a debugger

When you are execute a program that does not behave as you like, you need some way to step through you logic other than just looking at your code. Some things you want to know are:

Starting GDB

You need to tell the gcc compiler that you plan to debug your program. You use the -g flag to do this. The command will now look like

gcc -g trees.c
which will create the default a.out executable. To run this under the control of gdb, you type

gdb a.out
This starts up the text interface to the debugger. It's much easier to use gdb under an IDE, but this the real gdb interface.

GDB commands

When gdb starts, your program is not actually running. It won't run until you tell gdb how to run it. Whenever the prompt appears, you have all the commands on the quick reference sheet available to you.

The goal of gdb is to give you enough info to pinpoint where your program crashes, and find the bad pointer that is the cause of the problem. Although the actual error probably occurred much earlier in the program, figuring out which variable is causing trouble is a big step in the right direction.

Don't get an RTFM. Use gdb.

If you have any questions, check out the full manual.