Datasheet

Book VIII
Chapter 1
Programming
in Linux
547
Exploring the Software-Development Tools in Linux
#include <stdio.h>
static char buf[256];
void read_input(char *s);
int main(void)
{
char *input = NULL; /* Just a pointer, no storage for string */
read_input(input);
/* Process command. */
printf(“You typed: %s\n”, input);
/* . . . */
return 0;
}
void read_input(char *s)
{
printf(“Command: “);
gets(s);
}
This program’s main function calls the read_input function to get a line of
input from the user. The read_input function expects a character array in
which it returns what the user types. In this example, however, main calls
read_input with an uninitialized pointer — that’s the bug in this simple
program.
Build the program by using gcc with the -g option:
gcc -g -o dbgtst dbgtst.c
Ignore the warning message about the gets function being dangerous; I’m
trying to use the shortcoming of that function to show how you can use gdb
to track down errors.
To see the problem with this program, run it and type test at the
Command: prompt:
./dbgtst
Command: test
Segmentation fault
The program dies after displaying the Segmentation fault message. For
such a small program as this one, you can probably find the cause by exam-
ining the source code. In a real-world application, however, you may not
immediately know what causes the error. That’s when you have to use gdb
to find the cause of the problem.
To use gdb to locate a bug, follow these steps:
1. Load the program under gdb.
For example, type gdb dbgtst to load a program named dbgtst in
gdb.
42_770191-bk08ch01.indd 54742_770191-bk08ch01.indd 547 8/6/10 9:51 AM8/6/10 9:51 AM