Next: Finding More Information
Up: Debugging with GNU Debugger
Previous: Compiling with Debugging Information
Running GDB
You can start up gdb by typing:
% gdb reciprocal
When gdb starts up, you should see the GDB prompt:
(gdb)
The first step is to run your program inside the debugger. Just enter the command run and any program arguments.
(gdb) run
Starting program: reciprocal
Program received signal SIGSEGV, Segmentation fault.
__strtol_internal (nptr=0x0, endptr=0x0, base=10, group=0)
at strtol.c:287
287 strtol.c: No such file or directory.
(gdb)
The problem is that there is no error-checking code in main. The program expects one argument, but in this case the program was run with no arguments. The SIGSEGV message indicates a program crash. GDB knows that the actual crash happened in a function called __strtol_internal. That function is in the standard library, and the source is not installed, which explains the "No such file or directory" message.You can see the stack by using the where command:
(gdb) where
#0 __strtol_internal (nptr=0x0, endptr=0x0, base=10, group=0)
at strtol.c:287
#1 0x40096fb6 in atoi (nptr=0x0) at ../stdlib/stdlib.h:251
#2 0x804863e in main (argc=1, argv=0xbffff5e4) at main.c:8
You can see from this display that main called the atoi function with a NULL pointer, which is the source of the trouble. You can go up two levels in the stack until you reach main by using the up command:
(gdb) up 2
#2 0x804863e in main (argc=1, argv=0xbffff5e4) at main.c:8
8 i = atoi (argv[1]);
You can view the value of variables using the print command:
(gdb) print argv[1]
$2 = 0x0
That confirms that the problem is indeed a NULL pointer passed into atoi. You can set a breakpoint by using the break command:
(gdb) break main
Breakpoint 1 at 0x804862e: file main.c, line 8.
This command sets a breakpoint on the first line of main. Now try rerunning the program with an argument, like this:
(gdb) run 7
Starting program: reciprocal 7
Breakpoint 1, main (argc=2, argv=0xbffff5e4) at main.c:8
8 i = atoi (argv[1]);
You can see that the debugger has stopped at the breakpoint. You can step over the call to atoi using the next command:
(gdb) next
9 printf ("The reciprocal of %d is %g\n", i, reciprocal (i));
If you want to see what is going on inside reciprocal, use the step command like this:
(gdb) step
reciprocal (i=7) at reciprocal.cpp:6
6 assert (i != 0);
You are now in the body of the reciprocal function.
Next: Finding More Information
Up: Debugging with GNU Debugger
Previous: Compiling with Debugging Information
Cem Ozdogan
2007-02-19