GDB -- The GNU Debugger

The GNU debugger (GDB) allows a programmer to examine the internal operation of a running program. Variables and expressions can be printed and values changed. The program can be executed a line at a time or be forced to pause at specific locations. For programs that step outside the bounds of properly allocated memory, GDB can run a program while constantly watching specified memory location to see when they change. GDB is also useful to perform a post-mortem analysis of a program that has crashed and left behind a core file (more below).

GDB is best used with programs that have been compiled using the -g option. This places information in the executable code that lets the debugger know which parts of the executable correspond to which lines in source code files, which memory locations correspond to which variable names, and so forth. Programs compiled with the -g option are usually larger and slower than they would be otherwise.

GDB is used by typing in commands at a prompt. To reduce the amount of typing, most commands have abbreviations, many as small a single letter. Because some commands are used successively, GDB has the feature that when an empty command line is entered (no characters, just the return key) it will repeat the previous command. This point is important to understand in the efficient use of GDB.

The GDB commands fall naturally into several categories. An explanation of how to start gdb and a description of some of the most common commands is given below. Where they exist, the command abbreviations are given as well.

Invocation

GDB is started by typing gdb on the command line along with the name of the executable file to be debugged. If the program takes command line arguments, they are not given here. A splash message is displayed and then the GDB prompt is given, (gdb). This does not actually run the executable, but loads it in preparation for execution.

Running a Program

The commands for starting and stopping a program are given below.

Examining Data

Breakpoints

Breakpoints are places in the program being examined where the execution is forced to stop. Breakpoints can be inserted and deleted during a debugging session. No changes are made to the source code. Temporary breakpoints can also be created, which exist only until they are encountered the first time.

Watchpoints

Watchpoints are used to examine the value of an expression at every step of the program, stopping whenever the value of the expression changes. Watchpoints are invaluable in finding out what function is trashing a particular section of memory that should not be changing. Because the watchpoint is examined with every step of the program, watchpoints make a program hundreds or thousands of times slower. But sometimes they are the best tool for the job.

Watchpoints are listed using the info break command described above.