Easiest way to locate a Segmentation Fault

+1 for Tibors answer.

On larger programs or if you use additional libraries it may also be useful look at the backtrace with gdb: ftp://ftp.gnu.org/pub/old-gnu/Manuals/gdb/html_node/gdb_42.html


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.


The easiest way is to use valgrind. It will pinpoint to the location where the invalid access occours (and other problems which didn't cause crash but were still invalid). Of course the real problem could be somewhere else in the code (eg: invalid pointer), so the next step is to check the source, and if still confused, use a debugger.