Laboratory Exercises, C++ Programming
Laboratory Exercises, C++ Programming
Laboratory Exercises, C++ Programming
You also want an ePaper? Increase the reach of your titles
YUMPU automatically turns print PDFs into web optimized ePapers that Google loves.
16 Tools for Practical <strong>C++</strong> Development<br />
(gdb) is a command prompt.<br />
The first step is to run the program inside the debugger. Enter the command run and the program<br />
arguments. First run the program without arguments, like this:<br />
(gdb) run<br />
Starting program: /h/dd/c/.../reciprocal<br />
Program received signal SIGSEGV, Segmentation fault.<br />
*__GI_____strtol_l_internal (nptr=0x0, endptr=0x0, base=10, group=0, loc=0xb7f1c380)<br />
at strtol_l.c:298<br />
...<br />
The error occurred in the strtol l internal function, which is an internal function that atoi<br />
calls. Inspect the call stack with the where command:<br />
(gdb) where<br />
#0 *__GI_____strtol_l_internal (nptr=0x0, endptr=0x0, base=10, group=0, loc=0xb7f1c380)<br />
at strtol_l.c:298<br />
#1 0xb7e07fc6 in *__GI_strtol (nptr=0x0, endptr=0x0, base=10) at strtol.c:110<br />
#2 0xb7e051b1 in atoi (nptr=0x0) at atoi.c:28<br />
#3 0x080487b0 in main (argc=1, argv=0xbfa1be44) at reciprocal.cc:9<br />
You see that the atoi function was called from main. Use the up command (three times) to go to<br />
the main function in the call stack:<br />
...<br />
(gdb) up<br />
#3 0x080487b0 in main (argc=1, argv=0xbfa1be44) at reciprocal.cc:9<br />
9 int i = std::atoi(argv[1]); // atoi: "ascii-to-integer"<br />
Note that GDB finds the source code for main, and it shows the line where the function call<br />
occurred.<br />
You can examine the value of a variable using the print command:<br />
(gdb) print argv[1]<br />
$1 = 0x0<br />
This confirms a suspicion that the problem is indeed a 0 pointer passed to atoi. Set a breakpoint<br />
on the first line of main with the break command:<br />
(gdb) break main<br />
Breakpoint 1 at 0x80487a0: file reciprocal.cc, line 9.<br />
Now run the program with an argument:<br />
(gdb) run 5<br />
The program being debugged has been started already.<br />
Start it from the beginning? (y or n) y<br />
Starting program: /h/dd/c/.../reciprocal 5<br />
Breakpoint 1, main (argc=2, argv=0xbff7aae4) at reciprocal.cc:9<br />
9 int i = std::atoi(argv[1]); // atoi: "ascii-to-integer"<br />
The debugger has stopped at the breakpoint. Step over the call to atoi using the next command: