Search code examples
c#exceptionrecursionstack-overflow

stackoverflow by a recursion


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.


Solution

  • The problem is indeed stack overflow.

    Why it happens:

    The stack is a special memory region, where there are a few things stored:

    • local variables for functions
    • function parameters
    • (most importantly) function return addresses. When you return from a function, this is how the processor knows where to get back.

    The problem is that this memory region is limited. Recursive calls will add a significant amount of data on this stack, quickly filling it.

    How to fix it:

    There are several ways:

    • reduce the number of variables, if you have a local array in a recursive function, you are looking for trouble.
    • reduce the number of parameters for the function (apparently not the case here)
    • reduce the number of recursive calls.

    If this is not enough, the only solution is to find an iterative solution.