Ever had those annoying SEGMENTATION FAULT errors? Ever screamed in frustration because you weren't able to find their cause? Don't worry, GDB to the rescue!
#A faulty program
We have this C program: (prog1.c
)
#include <stdio.h>
int
main()
{
char buf[16], *c;
puts("Input some string!");
scanf("%s", buf);
for(c=buf; *c; c++); /* go to the end of the string */
puts("Here is your reversed string:");
while(c!=buf) {
c--;
putchar(*c);
}
return 0;
}
It's a pretty straightforward case. This program reverses strings, but if we input a string longer than 15 characters (the last position is a null character) we're overstepping the buffer boundaries. If the string is long enough, we overstep the program's boundaries and cause a segmentation fault.
Let's compile this and run it a few times:
$ gcc prog1.c
$ ./a.out
Input some string!
blargh
Here is your reversed string:
hgralb
$ ./a.out
Input some string!
thisstringisverylonghasmorethan16letters
Here is your reversed string:
ÐW¸msahgnolyrevsignirtssiht
Segmentation fault
Oops, what happened? The program received SIGSEGV
? Time to use gdb
!
#How to find the bug First, we compile the program with debug symbols
$ gcc -g prog1.c
and then run it through gdb
:
$ gdb ./a.out
[...]
Reading symbols from ./a.out...done.
(gdb) run
Starting program: $(pwd)/a.out
Input some string!
124567890124567890124567890124567890124567890124567890124567890124567890124567890124567890124567890124567890124567890124567890124567890124567890124567890124567890124567890124567890124567890124567890124567890124567890
Here is your reversed string:
�ÿÿÿÝÈ765421098765421098765421
Program received signal SIGSEGV, Segmentation fault.
0x00000000004006ae in main () at prog1.c:18
18 }