next up previous
Next: An example in Up: Tracing code Previous: Tracing code

An example in C

When you want to know what exactly is happening in your program, you have to trace it with the debugger. To do this, use the following commands in GDB (the abbreviation of a command is given between parentheses):

With the program bug, a debugging session could look like this:

 gdb bug
GDB is free software and you are welcome to 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.
GDB 4.13 (sparc-sun-solaris2.3), 
Copyright 1994 Free Software Foundation, Inc...
(gdb) break main
Breakpoint 1 at 0x106cc: file bug.c, line 14.
(gdb) run
Starting program: /home/se/doc/debug/source/bug 
 
Breakpoint 1, main () at bug.c:14
14          int a = 5;
(gdb) print &a
$1 = (int *) 0xeffff944
(gdb) next
15          int* ptr = 0;
(gdb) next
17          printptr(&a);
(gdb) next
5
18          printptr(ptr);
(gdb) step
printptr (iptr=0x0) at bug.c:8
8           printf("%d\n", *iptr);
(gdb) print iptr
$2 = (int *) 0x0
(gdb) step
 
Program received signal SIGSEGV, Segmentation fault.
0x106b4 in printptr (iptr=0x0) at bug.c:8
8           printf("%d\n", *iptr);
(gdb) list
3       #include <stdio.h>
4
5
6       void printptr(int* iptr)
7       {
8           printf("%d\n", *iptr);
9       }
10
11
12      int main()
(gdb) quit
The program is running.  Quit anyway (and kill it)? (y or n) y



SE Praktikum
Tue Aug 13 11:13:23 MET DST 1996