HiveBrain v1.2.0
Get Started
← Back to all entries
patterncppCritical

Determine the line of code that causes a segmentation fault?

Submitted by: @import:stackoverflow-api··
0
Viewed 0 times
linedeterminethesegmentationcausesfaultthatcode

Problem

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?

Solution

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

(gdb) backtrace


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.

Code Snippets

gcc program.c -g
$ gdb ./a.out
(gdb) run
<segfault happens here>
(gdb) backtrace
<offending code is shown here>

Context

Stack Overflow Q#2876357, score: 371

Revisions (0)

No revisions yet.