7.6. 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.


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.


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


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.


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.


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


Stop gdb.