Rask
Rask

Reputation: 477

What factors cause stack overflow exceptions in .NET?

I have an algorithm that uses deep recursion. How many levels deep the recursion will go varies and depends on the input. To avoid stack overflow exceptions I keep count of the depth and terminate at a specific depth.

By a bit of experimentation I previously established that a level of 500 was the point at which to stop. However, now suddenly I get stack overflow exceptions at levels just over 300.

Can anyone shed a bit of light on which factors would affect this? Is it e.g. CPU and RAM? Or related to which other processes is running on the computer?

Upvotes: 2

Views: 5060

Answers (3)

Nikhil Agrawal
Nikhil Agrawal

Reputation: 26538

This Explaination is the basic reason behind StackOverflowException for languages java, C, C++.

Stackoverflow exception is caused genrally in any language due to recursive method calls.

Suppose you have an method which is calling itself or any other method for an infinite recursive loop then it will cause a Stacoverflowexception. The reason behind this is the method call stack gets filled and it wont be able to accommodate any other method call.

Method call stack looks like this picture.

enter image description here

Explanation -- Suppose Main method has five statements And third method has an call to methodA, then the execution of main method gets paused at statement3 and MethosA will be loaded into call stack. Then method A has a call to methodB. So methodB also gets loaded into the stack.

So in this way infinite recursive calls makes call stack getting filled. So it cant afford any more methods. So it throws StackOverflowException.

Upvotes: 2

MikeP
MikeP

Reputation: 7959

You get a StackOverflowException when you run out of stack space. Calling a method uses some stack space (called a stack frame), as does local variables used during that function. Recursion continually adds new stack frames without popping the old ones off (unless you're employing tail-call optimization, which C# doesn't do too well at).

Therefore, exactly when this will occur is dependent upon the number of method calls as well as what you're doing inside these methods.

Upvotes: 4

Gabriel Magana
Gabriel Magana

Reputation: 4536

The answer varies, see here: Stack capacity in C#

You would be wise to change your algorithm to not be recursive, it will not be easy to see how much you can recurse, and basically you are tempting fate if you attempt to predict a certian level of recursion depth. That and whatever estimation algorithm you use for the stack depth might break with the next .NET service pack.

Upvotes: 1

Related Questions