14D. Avoiding the Swamp: Using a Debugger

A debugger allows you to run your program with extra capabilities that allow you to stop the program and inspect where it is and see the values of variables. If there is an error, such as a memory fault, you can see where the error occurred.

An integrated development environment has a debugger built into it, and you can find out how to use it by reading the documentation for the development environment. Here, I describe a free-standing debugger called gdb that is available with Linux.

First, before using gdb, compile your program with option -g. That will cause information for the debugger to be written into the machine language translation of your program. After compiling your program, suppose that you have an executable file called myprog. Then issue command

  gdb ./myprog
The debugger will start and give you a prompt asking what you want to do. To run the program, write what would be a command line for it, but replace the command with run. For example, gdb command
  run stuff.txt >output.txt
runs your executable program as if run by command
  ./myprog stuff.txt >output.txt
except that the debugger is in control of it.

Typing control-C will not stop the program, but only pause it. Then gdb will show a prompt, asking you what you want to do. Here is a short list of commands that gdb allows.

bt

This is short for backtrace. It shows the run-time stack, with a line for each frame. If there are a lot of frames, it pauses after each pageful. Press a space to see the next page, or q to quit.

up

You are always inspecting a single frame. Initially, the current frame is the top one (frame 0). Command up moves to the next higher-numbered frame. Command up 2 moves up two frames. Use any positive integer after up, as in
  up 3

down

Command down is similar to up, but it moves down a frame (or a given number of frames).

print E

Show the value of expression E. Gdb knows most of the syntax that C++ allows for expressions, but do not use function calls. Variables in the expression can either be variables in the current frame or global variables.

call E

Run function-call expression E.

break fun

Stop the program each time it calls function fun.

continue

Resume running the program after pausing it. You can use abbreviation cont.

(empty line)

Just type the enter key, without a command, to repeat the previous command.

help

Ask for help. You will get a list of topics. Command
  help topic
describes commands under the given topic.

quit

Stop gdb.


Exercises

  1. How do you start the gdb debugger on file ./hailstone? Answer

  2. When using gdb, how do you stop your program if you suspect that it is in an infinite loop? Answer

  3. When using gdb, how do you make the program pause whenever it enters function grape? Answer

  4. When using gdb, how do you resume a program after it pauses? Answer

  5. How do you exit gdb? Answer