GNU Debugger Overview

In order to use gdb on your program, you should provide an additional command line parameter to g++ when you compile your application: -g. This command line parameter tells g++ include debugging data in the executable produced.
    g++ -Wall -g example.C -o example
This produces an executable named example that works just like any other program you've compiled. The only difference is that the debugging data for this program is included in this file.

Now we can run our example program:

    Segmentation fault
Here, gdb comes to the rescue! We can use gdb to try to identify what's wrong with our program. To run gdb on your program, type: gdb <program>
    gdb example
Now, we get a (gdb) prompt:
At this prompt, to run our program, we type run:
    (gdb) run
    Starting program: /u/csgs/ard/classes/2440/example 

    Program received signal SIGSEGV, Segmentation fault.
    basic_string, __default_alloc_template >::rep (this=0x0)
        at /usr/local/gcc/gcc-2.95.3/lib/gcc-lib/alphaev6-dec-osf5.1/2.95.3/../../../../include/g++-3/std/bastring.h:147
    147       Rep *rep () const { return reinterpret_cast(dat) - 1; }
Here, we see that this is equal to zero. Since this is a self-pointing pointer, the value should be an address. That address should never be zero (as it is in this example). It looks like we're dereferencing a null pointer. Now how do we determine where we did that? Well, there is another gdb command that will give us a printout of the function stack trace:
    (gdb) bt
    #0  basic_string, __default_alloc_template >::rep (this=0x0)
        at /usr/local/gcc/gcc-2.95.3/lib/gcc-lib/alphaev6-dec-osf5.1/2.95.3/../../../../include/g++-3/std/bastring.h:147
    #1  0x12000b49c in basic_string, __default_alloc_template >::data (this=0x0)
        at /usr/local/gcc/gcc-2.95.3/lib/gcc-lib/alphaev6-dec-osf5.1/2.95.3/../../../../include/g++-3/std/bastring.h:152
    #2  0x12000b400 in __ls__H3ZcZt18string_char_traits1ZcZt24__default_alloc_template2b0i0_R7ostreamRCt12basic_string3ZX01ZX11ZX21_R7ostream (o=@0x1400038c8, 
        at /usr/local/gcc/gcc-2.95.3/lib/gcc-lib/alphaev6-dec-osf5.1/2.95.3/../../../../include/g++-3/std/
    #3  0x12000b37c in main () at example.C:7
We see several methods that do not look familiar. These are methods internal to a library we're using. If we continue to follow the stack trace back, we see a reference to a function that is in our program, here in function main in file example.C, line 7.

Now, try compiling this example and use gdb to fix the errors.

See the GDB Quick Reference for further commands to use while debugging and My GDB Tutorial.