Search code examples
c#c++recursionstack-overflow

Difference between c++ and c# in stack overflow exception


While I was writing some code in C#, I had a recursive method which caused a stack overflow exception after a couple thousand calls.
So after a while, I wrote the same code in C++ and it worked fine with no exceptions (even though the actual number of recursive calls is about 10 times more than from where C# stopped).
What is the difference between C# and C++ in handling this? And is there any way I can allow for more recursive calls in C# without the exception being thrown?


Solution

  • The most notable difference of stackoverflow in C# and C++ is: C++ doesn't have a "stack overflow exception" (*). The result of overflowing the stack with C++ is just undefined behavior. It may do what you expect it to do but it may also do something entirely different. If you go lucky, the program crashes (with a segmentation violation because a protected page was allocated at the end of the stack) and if you go unlucky the stackoverflow isn't detected until at some point an attempt is made to access now overwritten memory.

    Other things which may factor into recursive calls:

    1. The available stack sizes may be different.
    2. The sizes of the used stack frames are likely to be different.
    3. Tail recursion optimizations may be done in one case but not the other.
    4. Some systems are capable of dynamically increasing their stack ("split stack").

    (*) As the behavior is undefined, some implementations may define a stackoverflow exception and throw that under appropriate conditions; however, there is no such guarantee.