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.
Use a debugger, such as
gdbor if this is not applicable astracetool to get a better insight into where the segfault occurs.If you use
gcc, make sure you compile with-gswitch to include debugging information. Then,gdbwill show you the exact location in a source code where it segfaults.For example, if we have this obvious segfaulty program:
new.c
We compile it with
gcc -g new.c -o newand then run thegdbsession withgdb new:We issue the
runcommand in the interactive session and the else is clear:As DasMoeh and netcoder have pointed out, when segfault has occured, you can use the
backtracecommand in the interactive session to print a call stack. This can aid in further pinpointing the location of a segfault.