Usage of gdb

Take the following code

#include <iostream>

using std::cout;
using std::endl;

void do_stuff(void) {
    int *i;

    i = NULL;
    *i = 1;
}

int main(void) {
    cout << "Hello world" <<endl;
    do_stuff();
    return 0;
}

And if you run it you get:
 iam4@voodoo:~/208$ ./test
 Hello world
 Segmentation fault

Where did the segmentation fault come from? This is where a debugger can help you.

To use the debugger compile the code as follows:
 g++ -g -Wall test.cpp -o test

The -Wall options runs with all warnings on and -g says to put debug symbols in.
 
Now start up gdb by doing the following:
 gdb test

You will now be at a prompt like (gdb).

Useful commands are:
run - start the program (put arguments after this if your program expects command line arguments)
help - gives quite useful help
list - shows the program source code
next - go forward one line of code and stop (goes into function calls)
step - go forward one line of code and stop (does not go into function calls)
cont - continue running until next breakpoint or program completes
break - you can insert a point where the program pauses so that you can do things. e.g. For above program you can do the following for it to stop at the start of do_stuff subroutine:

(gdb) break do_stuff
Breakpoint 1 at 0x80486ea: file test.cpp, line 9.
(gdb) run
Starting program: /home/iam4/208/test
Hello world

Breakpoint 1, do_stuff () at test.cpp:9
9               i = NULL;
(gdb)

When a program crashes if you are using gdb it will output where it crashed and show you the code.
Program received signal SIGSEGV, Segmentation fault.
0x080486f4 in do_stuff () at test.cpp:10
10              *i = 1;

If your program hangs you can use Ctrl-C key combination for your program to stop execution and gdb will show you where the code is currently running.

Often it can be useful to find out what called your function so you can use the backtrace command as follows:
(gdb) backtrace
#0  0x080486f4 in do_stuff () at test.cpp:10
#1  0x08048735 in main () at test.cpp:15

You can use print and printf to print out variable values. printf uses 'C' formatting strings. For example:

(gdb) print i
$1 = (int *) 0x5556bed8
(gdb) printf "%p\n",i
0x5556bed8
(gdb) printf "%d\n",i
1431748312

Remember to read the documentation as there is lots more to do and it makes it much easier to find your bugs!

Links:
Another gdb tutorial
WLUG article on debugging
IBM article on gdb and strace
IBM article on gdb macros

Back to my home page

Last modified 9th November 2006