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

后端 未结 12 1518
不知归路
不知归路 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:44

    Keep trying to return main until the stack runs out?

    int main(int argc, char **argv)
    {
        return main(argc, argv);
    }
    
    0 讨论(0)
  • 2020-12-31 19:44

    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.

    0 讨论(0)
  • 2020-12-31 19:47

    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];
    
    }
    
    0 讨论(0)
  • 2020-12-31 19:49

    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;
    }
    
    0 讨论(0)
  • 2020-12-31 19:51

    Infinite recursion:

    void infiniteFunction()
    {
        infiniteFunction();
    }
    
    int main()
    {
        infiniteFunction();
        return 0;
    }
    
    0 讨论(0)
  • 2020-12-31 19:52

    You could also get a stack overflow if you try to put large objects on the stack (by-value).

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