递归 main() - 为什么会出现段错误?
为什么下面的程序会出现段错误?
int main() { main(); }
尽管它是一个不会结束的递归,因此根据定义是无效的,但我不明白为什么它会出现段错误(gcc 4.4.3 和 clang 1.5 (trunk))。
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)).
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(6)
您会遇到堆栈溢出(!)
You get a stack overflow (!)
因为每次它调用自己时都会分配一点堆栈空间;最终它会耗尽堆栈空间并出现段错误。不过,我有点惊讶它会出现段错误;我本来期望(鼓声)堆栈溢出!
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!
会导致堆栈溢出。
但是,
像这样的优化版本(不是调试模式):
将在尾递归调用中转换递归,也称为无限循环!
will cause a stack overflow.
But,
an optimized version (not debug mode) like this:
will transform the recursion in a tail-recursive call, aka an infinite loop!
它是没有基本情况的递归,这会导致堆栈溢出
it is recurse without a base case, which causes a stack overflow
它会导致堆栈溢出,并被诊断为系统上的段错误。
It leads to stack overflow that is diagnosed as segfault on your system.
每个函数调用都会在堆栈中添加整个条目,当函数退出时,这些条目将从堆栈中删除。
这里我们有没有退出条件的递归函数调用。因此,它是一个接一个的无限次函数调用,并且该函数永远不会退出,并且整个函数永远不会从堆栈中删除,这将导致堆栈溢出。
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.