Skip to content

Instantly share code, notes, and snippets.

@rhaps0dy
Last active August 29, 2015 14:03
Show Gist options
  • Save rhaps0dy/3c5c51073c64672fb4d4 to your computer and use it in GitHub Desktop.
Save rhaps0dy/3c5c51073c64672fb4d4 to your computer and use it in GitHub Desktop.
HOWTO: Catch segmentation faults on gdb (GNU debugger)

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	}
#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;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment