Can you give an example of stack overflow in C++?

后端 未结 12 1607
不知归路
不知归路 2020-12-31 18:52

Can you give an example of stack overflow in C++? Other than the recursive case:

void foo() { foo(); }
12条回答
  •  醉酒成梦
    2020-12-31 19:31

    Here's one that might happen in practice:

    int factorial(int x) {
      return x == 0 ? 1 : x * factorial(x-1);
    }
    

    This overflows the stack for negative x. And, as Frank Krueger mentioned, also for too large x (but then int would overflow first).

提交回复
热议问题