Programming in C

(Barry) #1
Debugging Programs with gdb 397

When gdbis ready to accept commands, it displays a (gdb)prompt. In our simple
example, you’re simply telling it to run your program by entering the runcommand.
This causes gdbto start execution of your program until it finishes or an abnormal event
occurs:


(gdb) run
Starting program: /Users/stevekochan/MySrc/c/a.out
Reading symbols for shared libraries. done


Program received signal EXC_BAD_ACCESS, Could not access memory.
0x00001d7c in main () at p18-4.c:9
9 sum += data[i];
(gdb)


So your program receives an error (as it did before), but it still remains under the control
of gdb.That’s the nice part because now you can see what it was doing when the error
occurred as well as look at the values of variables at the time of the error.
As you can see from the previous display, the program tried to perform an invalid
memory access at line 9 in your program.The actual line in question is automatically
displayed from your source file.To gain a little context around that line, you can use the
listcommand, which displays a window of 10 lines around the specified line (5 lines
before and 4 lines after):


(gdb) list 9
4 {
5 const int data[5] = {1, 2, 3, 4, 5};
6 int i, sum;
7
8 for (i = 0; i >= 0; ++i)
9 sum += data[i];
10
11 printf ("sum = %i\n", sum);
12
13 return 0;
(gdb)


You can look at variables by using the printcommand.Take a look at what the value of
sumwas at the time the program stopped with an error:


(gdb) print sum
$1 = -1089203864


This value for sumis obviously out of whack (and on your system might differ from
what’s shown here).The $nnotation is used by gdbto keep track of the values you’ve
previously displayed, so you can easily reference them again later.
Ta ke a look at what the index variable iis set to:


(gdb) print i
$2 = 232

Free download pdf