Why does this C++ code-snippet segmentation fault?

半城伤御伤魂 提交于 2019-12-11 02:21:39

问题


#include <iostream>
using namespace std;

int recur(int x) {
    1 and recur(--x);
    cout << x;
    return x;
}

int main() {
    recur(10);
    return 0;
}

回答1:


1 and recur(--x);

is equivalent to

recur(--x);

Clearly you are making infinite recursive calls which leads to stack overflow followed by segmentation fault.

I guess you meant

  x and recur(--x);

which makes the recursive call only when x is non-zero.




回答2:


Thats an infinite recursion. So it will seg fault when it runs out of stack space.




回答3:


It doesn't have a termination condition for the recursion, and so will recurse until you run out of stack space.




回答4:


recur is an infinite loop; you need to put a base condition on there so it stops calling itself.
E.g. (at the top of the function) if (x <= 0) return 0;

Also, what's the point of the 1 and ? It's a no-op... maybe you meant x and, which would stop the recursion when x reached 0, provided you only ever called recur with a positive number (negative values would still cause the infinite loop).



来源:https://stackoverflow.com/questions/2809014/why-does-this-c-code-snippet-segmentation-fault

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!