Datasheet

Book VIII
Chapter 1
Programming
in Linux
549
Exploring the Software-Development Tools in Linux
At this point, you can narrow the problem to the variable named input.
That variable is an array, not a NULL (which means zero) pointer.
Fixing bugs in gdb
Sometimes you can fix a bug directly in gdb. For the example program in the
preceding section, you can try this fix immediately after the program dies
after displaying an error message. An extra buffer named buf is defined in
the dbgtst program, as follows:
static char buf[256];
We can fix the problem of the uninitialized pointer by setting the variable
input to buf. The following session with gdb corrects the problem of the
uninitialized pointer. (This example picks up immediately after the program
runs and dies, due to the segmentation fault.)
(gdb) file dbgtst
A program is being debugged already. Kill it? (y or n) y
Load new symbol table from “/home/edulaney/sw/dbgtst”? (y or n) y
Reading symbols from /home/edulaney/sw/dbgtst . . . done.
(gdb) list
1 #include <stdio.h>
2 static char buf[256];
3 void read_input(char *s);
4 int main(void)
5 {
6 char *input = NULL; /* Just a pointer, no storage for string */
7 read_input(input);
8 /* Process command. */
9 printf(“You typed: %s\n”, input);
10 /* . . . */
(gdb) break 7
Breakpoint 2 at 0x804842b: file dbgtst.c, line 7.
(gdb) run
Starting program: /home/edulaney/sw/dbgtst
Breakpoint 1, main () at dbgtst.c:7
7 read_input(input);
(gdb) set var input=buf
(gdb) cont
Continuing.
Command: test
You typed: test
Program exited normally.
(gdb)q
As the preceding listing shows, if the program is stopped just before read_
input is called and the variable named input is set to buf (which is a valid
array of characters), the rest of the program runs fine.
After finding a fix that works in gdb, you can make the necessary changes to
the source files and make the fix permanent.
42_770191-bk08ch01.indd 54942_770191-bk08ch01.indd 549 8/6/10 9:51 AM8/6/10 9:51 AM