Determine the line of code that causes a segmentation fault?

user319824 picture user319824 · May 20, 2010 · Viewed 200.2k times · Source

How does one determine where the mistake is in the code that causes a segmentation fault?

Can my compiler (gcc) show the location of the fault in the program?

Answer

nc3b picture nc3b · May 20, 2010

GCC can't do that but GDB (a debugger) sure can. Compile you program using the -g switch, like this:

gcc program.c -g

Then use gdb:

$ gdb ./a.out
(gdb) run
<segfault happens here>
(gdb) backtrace
<offending code is shown here>

Here is a nice tutorial to get you started with GDB.

Where the segfault occurs is generally only a clue as to where "the mistake which causes" it is in the code. The given location is not necessarily where the problem resides.