Question:
Segmentation fault in C program, seems to destroy everything I try?
2007-03-08 18:34:56 UTC
I've been recieving a horrid segmentation fault when writing a C program. I decided to have the program print a line at the very beginning of the main function, but the line doesn't even print, I just get this god-blessed segmentation fault! The program is written in pico in unix, otherwise I'd copy it - however, I don't think the code is important, just a lead as to where and why this Effing segmentation fault is able to ruin the program before it begins.
Four answers:
Dan M
2007-03-08 19:22:23 UTC
The printf() probably uses buffered I/O. This means that the print output is placed in a buffer and will eventually make it to the screen. So the program dumps the output into the buffer and moves on. Maybe the program is hitting the fault before the buffer gets flushed to the screen.



When you hit a segmentation fault usually a core dump is produced. This is an image of memory when the problem occured. There are tools that can look at the core dump and tell you where it crashed.



Compile the program with -g to turn on debugging symbols.

Also use -Wall to turn on maximum warnings.



use "gdb executable_name" to run the program. I forget the

gdb command to execute the program - you will have to look it up. gdb will give you more info when the program faults.
rsmith985
2007-03-08 19:13:33 UTC
Segmentation faults are caused by referencing memory outside your program. Probably caused by a some kind of pointer. Make sure you arent deleting pointers that have already been dereferenced and make sure you arent pointing to somewhere you shouldnt be.



As for why you arent seeing the output. Is it pausing after you print it somehow. It may print but you never see it because your program fails later on and it happens so fast you never notice it print.
icnintel
2007-03-09 16:57:33 UTC
Highly recommend that you step through with gdb and check all your variables to see where they point. If you can't do that then carpet-bomb your code with print statements. I agree with others here: segmentation fault almost always means you're dereferencing a bad pointer OR you are passing a bad pointer to a function, which is then dereferencing it.
2007-03-08 18:59:34 UTC
Your best bet is to go to a C programming or Pico forum and ask there. I'm assuming you've looked through the docs in /usr/share/docs - or whatever it is on UNIX (I'm a Linux user, but I don't program).


This content was originally posted on Y! Answers, a Q&A website that shut down in 2021.
Loading...