I have a long program in c over Linux, that gives me segmentation fault after main returns. Its a long program, so I cant post it. So can you help me what can make such error?
Thank You.
Wow, Those answers came really fast. Thank you all. I think i worked it out, i forgot to malloc a string and used it as buffer. Now that I've malloced it, it does not signal me with a segmentation fault.
Once again, thank you all.
Use GDB and print stack trace on SIGSEGV signal. Then at least post that here so we can be a little bit more helpful.
Provided you compiled with:
Then run it under GDB:
When you get
SIGSEGV
signal (Segmentation Fault), do this:Then see what's on the stack trace to see what is causing the segmentation fault.
If the segmentation fault arises after main() returns, it usually means that a global defined thing went wrong. It is hard to help you with so little info. Send us more info !
my2c
Guess: you might be accidentally corrupting the stack in main so it's lost the return address. Do you have a string buffer there that you could be overrunning?
If not, you should try:
It might help to install glibc-debug packages if your distro has them since you'll be in glibc code at that point.
If it's after
main()
returns, then according to the Standard all destructors have been run (although I wouldn't put it past an implementation to fudge this some), unless the functionatexit()
has been used. That function registers a function that will be called aftermain()
returns, effectively (if I'm reading 3.6.3 aright). You might check to see if there is anatexit
in your program somewhere, if only for completeness.Depending on what you mean by "after main returns", you may be running destructors for static objects when the program crashes. Check those. (Also, post what you observed that made you think it was after
main()
returned. You could be wrong there.)If not, then you've invoked undefined behavior somewhere, very likely in corrupting the stack somehow. See Rup's answer for suggestions there.