Recursive main() - why does it segfault?

2019-02-08 21:42发布

Why does the following program segfault?

int main() { main(); }

Even though it is a recursion that does not end and is therefore invalid by definition, I don't see why it segfaults (gcc 4.4.3 and clang 1.5 (trunk)).

6条回答
戒情不戒烟
2楼-- · 2019-02-08 22:22

It leads to stack overflow that is diagnosed as segfault on your system.

查看更多
地球回转人心会变
3楼-- · 2019-02-08 22:26
int main() { main(); }

will cause a stack overflow.

But,

an optimized version (not debug mode) like this:

int main() {
   return main();
}

will transform the recursion in a tail-recursive call, aka an infinite loop!

查看更多
迷人小祖宗
4楼-- · 2019-02-08 22:27

Each function call add entires in stack and this entries will get removed from stack when function exit. Here we have recursive function call which doesn't have exit condition. So its a infinite number of function call one after another and this function never get exit and there entires never removed from the stack and it will lead to Stack overflow.

查看更多
萌系小妹纸
5楼-- · 2019-02-08 22:30

You get a stack overflow (!)

查看更多
Root(大扎)
6楼-- · 2019-02-08 22:39

Because every time it calls itself it allocates a little bit of stack space; eventually it runs out of stack space and segfaults. I'm a bit surprised it goes with a segfault, though; I would have expected (drum roll) stack overflow!

查看更多
姐就是有狂的资本
7楼-- · 2019-02-08 22:44

it is recurse without a base case, which causes a stack overflow

查看更多
登录 后发表回答