Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

stackoverflow by a recursion [duplicate]

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.

like image 820
Matan L Avatar asked Jul 03 '12 13:07

Matan L


3 Answers

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.

like image 180
Tibi Avatar answered Nov 02 '22 12:11

Tibi


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.

like image 40
Matthew Watson Avatar answered Nov 02 '22 11:11

Matthew Watson


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.

like image 2
Chris Mantle Avatar answered Nov 02 '22 10:11

Chris Mantle