Skip to content
Advertisement

Easiest way to locate a Segmentation Fault

I encountered my first Segmentation Fault today (newbie programmer). After reading up on what a segmentation fault is (Thanks for all of the helpful info on this site, as well as Wikipedia’s lengthy explanation), I’m trying to determine the easiest way to go about finding where my fault is occuring. It’s written in C and the error is occuring on a *NIX based system (I’m not sure which one to be honest… 99% sure it’s Linux). I can’t exactly post my code as I have numerous files that I’m compiling that are all quite lengthy. I was just hoping for some best practices you have all observed. Thanks for your help.

P.s. I’m thinking the error is coming from dereferencing a NULL pointer or using an uninitialized pointer. However, I could definitely be wrong.

Advertisement

Answer

Use a debugger, such as gdb or if this is not applicable a strace tool to get a better insight into where the segfault occurs.

If you use gcc, make sure you compile with -g switch to include debugging information. Then, gdb will show you the exact location in a source code where it segfaults.

For example, if we have this obvious segfaulty program:

new.c

#include <stdio.h>

int main()
{
        int *i = 0x478734;
        printf("%d", *i);
}

We compile it with gcc -g new.c -o new and then run the gdb session with gdb new:

We issue the run command in the interactive session and the else is clear:

(gdb) run
Starting program: /home/Tibor/so/new
[New Thread 9596.0x16a0]
[New Thread 9596.0x1de4]

Program received signal SIGSEGV, Segmentation fault.
0x0040118a in main () at new.c:6
6               printf("%d", *i);
(gdb)

As DasMoeh and netcoder have pointed out, when segfault has occured, you can use the backtrace command in the interactive session to print a call stack. This can aid in further pinpointing the location of a segfault.

User contributions licensed under: CC BY-SA
3 People found this is helpful
Advertisement