GDB Tutorial

source: http://www.cs.princeton.edu/~benjasik/gdb/gdbtut.html


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. There is complete documentation for GDB online, or you can read the man page, and the quick reference sheet is very handy.
 

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 lcc compiler that you plan to debug your program. You use the -g flag to do this. The command will now look like
 
 
lcc -g trees.c
which will create the 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 emacs, but we'll use this interface to describe the commands

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. Before you seek help from a TA or preceptor, you should try to figure out whereyour error is occurring

GDB under Emacs

Emacs provides a much better interface to gdb that saves a lot of typing and confusion. Executing the Emacs command M-x gdb starts up a new window running gdb. If you set a breakpoint on the main function and then run the program with the correct arguments, gdb will split the window in two, with your source code on the bottom and a gdb command line in the top. Emacs intercepts output from gdb and interprets it for you. When you stop at a breakpoint, Emacs will take the file and line number reported by gdb, and display the file contents, with the point of the breakpoint market. As you step through a program, Emacs will follow your pgoress in the source file. The command C-x SPC will place a breakpoint at the current point of the file you are in.

 If you have any questions, check out the online manual, or send me mail