Programming in C

(Barry) #1

396 Chapter 18 Debugging Programs


Your C program must be compiled with the gcccompiler using the -goption to
make full use of gdb’s features.The -goption causes the C compiler to add extra infor-
mation to the output file, including variable and structure types, source filenames, and C
statement to machine code mappings.
Program 18.4 shows a program that attempts to access elements past the end of an
array.

Program 18.4 A Simple Program for Use with gdb
#include <stdio.h>

int main (void)
{
const int data[5] = {1, 2, 3, 4, 5};
int i, sum;

for (i = 0; i >= 0; ++i)
sum += data[i];

printf ("sum = %i\n", sum);

return 0;
}

Here’s what happens when the program is run on a Mac OS X system from a terminal
window (on other systems you might get a different message displayed when you run
the program):
$ a.out
Segmentation fault
Use gdbto try to track down the error.This is certainly a contrived example; neverthe-
less, it is illustrative.
First, make sure you compile the program with the –goption.Then, you can start up
gdbon the executable file, which is a.outby default.This might result in lines of intro-
ductory messages being displayed on your system:
$ gcc –g p18.4.c Recompile with debugging information for gdb
$ gdb a.out Start up gdb on the executable file
GNU gdb 5.3-20030128 (Apple version gdb-309) (Thu Dec 4 15:41:30 GMT 2003)
Copyright 2003 Free Software Foundation, Inc.
GDB is free software, covered by the GNU General Public License, and you are
welcome to change it and/or distribute copies of it under certain conditions.
Type "show copying" to see the conditions.
There is absolutely no warranty for GDB. Type "show warranty" for details.
This GDB was configured as "powerpc-apple-darwin".
Reading symbols for shared libraries .. done
Free download pdf