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

后端 未结 12 1517
不知归路
不知归路 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).

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

    Compile-time example:

    template <int N>
    struct Factorial {
        enum { value = N * Factorial<N - 1>::value };
    };
    
    // ...
    {
        int overflow = Factorial<10>::value;
    }
    
    0 讨论(0)
  • 2020-12-31 19:35

    Please see Stack overflow - Wikipedia. I have linked directly to the examples section.

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

    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.

    0 讨论(0)
  • I can't believe we left off the greatest recursion example of all time, factorial!

    #include <stdio.h>
    
    double fact(double n) {
        if (n <= 0) return 1;
        else return n * fact(n - 1);
    }
    
    int main() {
        printf("fact(5) = %g\n", fact(5));
        printf("fact(10) = %g\n", fact(10));
        printf("fact(100) = %g\n", fact(100));
        printf("fact(1000) = %g\n", fact(1000));
        printf("fact(1000000) = %g\n", fact(1000000));
    }
    

    On OS X 10.5.8 with GCC 4.0.1:

    $ gcc f.c -o f && ./f
    fact(5) = 120
    fact(10) = 3.6288e+06
    fact(100) = 9.33262e+157
    fact(1000) = inf
    Segmentation fault
    

    Unfortunately, OS X reports a "Segmentation fault" instead of a "Stack overflow". Too bad.

    0 讨论(0)
  • 2020-12-31 19:44
    void function()
    {
     function();
    }
    
    0 讨论(0)
提交回复
热议问题