20.09.2015 Views

Programming in C

Kochan - ProgramminginC

Kochan - ProgramminginC

SHOW MORE
SHOW LESS

Create successful ePaper yourself

Turn your PDF publications into a flip-book with our unique Google optimized e-Paper software.

Debugg<strong>in</strong>g Programs with gdb<br />

397<br />

When gdb is ready to accept commands, it displays a (gdb) prompt. In our simple<br />

example, you’re simply tell<strong>in</strong>g it to run your program by enter<strong>in</strong>g the run command.<br />

This causes gdb to start execution of your program until it f<strong>in</strong>ishes or an abnormal event<br />

occurs:<br />

(gdb) run<br />

Start<strong>in</strong>g program: /Users/stevekochan/MySrc/c/a.out<br />

Read<strong>in</strong>g symbols for shared libraries . done<br />

Program received signal EXC_BAD_ACCESS, Could not access memory.<br />

0x00001d7c <strong>in</strong> ma<strong>in</strong> () at p18-4.c:9<br />

9 sum += data[i];<br />

(gdb)<br />

So your program receives an error (as it did before), but it still rema<strong>in</strong>s under the control<br />

of gdb.That’s the nice part because now you can see what it was do<strong>in</strong>g when the error<br />

occurred as well as look at the values of variables at the time of the error.<br />

As you can see from the previous display, the program tried to perform an <strong>in</strong>valid<br />

memory access at l<strong>in</strong>e 9 <strong>in</strong> your program.The actual l<strong>in</strong>e <strong>in</strong> question is automatically<br />

displayed from your source file.To ga<strong>in</strong> a little context around that l<strong>in</strong>e, you can use the<br />

list command, which displays a w<strong>in</strong>dow of 10 l<strong>in</strong>es around the specified l<strong>in</strong>e (5 l<strong>in</strong>es<br />

before and 4 l<strong>in</strong>es after):<br />

(gdb) list 9<br />

4 {<br />

5 const <strong>in</strong>t data[5] = {1, 2, 3, 4, 5};<br />

6 <strong>in</strong>t i, sum;<br />

7<br />

8 for (i = 0; i >= 0; ++i)<br />

9 sum += data[i];<br />

10<br />

11 pr<strong>in</strong>tf ("sum = %i\n", sum);<br />

12<br />

13 return 0;<br />

(gdb)<br />

You can look at variables by us<strong>in</strong>g the pr<strong>in</strong>t command.Take a look at what the value of<br />

sum was at the time the program stopped with an error:<br />

(gdb) pr<strong>in</strong>t sum<br />

$1 = -1089203864<br />

This value for sum is obviously out of whack (and on your system might differ from<br />

what’s shown here).The $n notation is used by gdb to keep track of the values you’ve<br />

previously displayed, so you can easily reference them aga<strong>in</strong> later.<br />

Take a look at what the <strong>in</strong>dex variable i is set to:<br />

(gdb) pr<strong>in</strong>t i<br />

$2 = 232

Hooray! Your file is uploaded and ready to be published.

Saved successfully!

Ooh no, something went wrong!