segmentation fault after main returns

2020-02-14 09:07发布

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.

4条回答
劳资没心,怎么记你
2楼-- · 2020-02-14 09:38

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:

$ gcc -g prog.c -o prog

Then run it under GDB:

$ gdb ./prog
gdb> r

When you get SIGSEGV signal (Segmentation Fault), do this:

gdb> bt

Then see what's on the stack trace to see what is causing the segmentation fault.

查看更多
做自己的国王
3楼-- · 2020-02-14 09:39

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

查看更多
小情绪 Triste *
4楼-- · 2020-02-14 09:46

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:

  • running the program under valgrind
  • debugging the program with gdb to catch the crash and see where you are at that point; you can also debug the core file dumped

It might help to install glibc-debug packages if your distro has them since you'll be in glibc code at that point.

查看更多
孤傲高冷的网名
5楼-- · 2020-02-14 10:01

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 function atexit() has been used. That function registers a function that will be called after main() returns, effectively (if I'm reading 3.6.3 aright). You might check to see if there is an atexit 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.

查看更多
登录 后发表回答