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

2019-02-07 06:17发布

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

void foo() { foo(); }

12条回答
狗以群分
2楼-- · 2019-02-07 06:26

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).

查看更多
够拽才男人
3楼-- · 2019-02-07 06:26

This example shows uncontrolled recursion. Eventually, the stack spaced allocated to this process will be completely overwritten by instances of bar and ret...

int foo( int bar )
{
    int ret = foo( 42 );
    return ret;
}
查看更多
成全新的幸福
4楼-- · 2019-02-07 06:29

Keep trying to return main until the stack runs out?

int main(int argc, char **argv)
{
    return main(argc, argv);
}
查看更多
劫难
5楼-- · 2019-02-07 06:31

The typical case that does not involve infinite recursion is declaring an automatic variable on the stack that is too large. For example:

int foo()
{
    int array[1000000];

}
查看更多
闹够了就滚
6楼-- · 2019-02-07 06:33

If you want to generate an explicitly non-recursive program to result in a stack overflow by function calls:

#!/usr/bin/env python
import sys

print "void func" + sys.argv[1] + "() { }"
for i in xrange(int(sys.argv[1])-1, -1, -1):
    print "void func" + str(i) + "() { func" + str(i+1) + "(); }"
print "int main() { func0(); return 0; }"

Sample output:

$ python recursion.py 5
void func5() { }
void func4() { func5(); }
void func3() { func4(); }
void func2() { func3(); }
void func1() { func2(); }
void func0() { func1(); }
int main() { func0(); return 0; }

Sample usage:

$ python recursion.py 250000 | g++ -x c++ - && ./a.out

At least on my system, the call stack seems to be 174602, so you'll need to set the argument to recursion.py to be larger than that; and it takes a few minutes to compile and link the program.

查看更多
淡お忘
7楼-- · 2019-02-07 06:34

As per edit :-)

void ping()
{
  pong();
}

void pong()
{
ping();
}

Also, I believe you can get stack overflow if you try to allocate more space than maximum thread stack size ( 1MB by default in VS), so something like int a[100000]; should provide the exception.

查看更多
登录 后发表回答