Recursive main() - why does it segfault?

后端 未结 6 687
青春惊慌失措
青春惊慌失措 2021-01-02 07:49

Why does the following program segfault?

int main() { main(); }

Even though it is a recursion that does not end and is therefore invalid by

相关标签:
6条回答
  • 2021-01-02 08:00

    You get a stack overflow (!)

    0 讨论(0)
  • 2021-01-02 08:00

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

    0 讨论(0)
  • 2021-01-02 08:02

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

    0 讨论(0)
  • 2021-01-02 08:14

    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.

    0 讨论(0)
  • 2021-01-02 08:18
    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!

    0 讨论(0)
  • 2021-01-02 08:20

    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!

    0 讨论(0)
提交回复
热议问题