Possible Duplicate:
Runtime exception, recursion too deep
I'm getting a problem while developing a c#.net program and I've simplified it to a simple problem, I need to understand why does this code throw a stackoverflow exception if I call the function like this :
CheckFunc(16000);
but works fine if I call it like this
CheckFunc(1000);
here is the function :
private void CheckFunc(Int32 i)
{
if (i == 0)
MessageBox.Show("good");
else
CheckFunc(i - 1);
}
tried to make the code as simple as it can get...
I understand that there is a stack that gets overflowed but which stack ? How can I fix this ?
Thanks.
The problem is indeed stack overflow.
The stack is a special memory region, where there are a few things stored:
The problem is that this memory region is limited. Recursive calls will add a significant amount of data on this stack, quickly filling it.
There are several ways:
If this is not enough, the only solution is to find an iterative solution.
It's because you simply don't have enough stack space to recurse 16000 times.
Recursion should almost invariably be to a MUCH lower level than that! Otherwise, rewrite as a loop. You CANNOT fix this any other way.
You need to read about the stack, and how it is used in program execution. In a nutshell, your function fails because it recursively calls itself too many times. The stack, like the heap, has a finite size, but unlike the heap, it is generally much smaller. Every time your function calls itself, some memory in the stack is used to hold information about the function call and variables local to the function (a reference to the variable i in your example). This is called a stack frame. When too many stack frames are created because the recursion is too deep, there is a stack overflow.
You should remove the recursion in CheckFunc, and call it from a loop instead.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With