Stackoverflow by recursion

Possible duplicate:
Runtime exception, recursion too deep

I have a problem when developing an aC # .net program, and I simplified it to a simple problem, I need to understand why this code throws a stackoverflow exception if I call the function as follows:

CheckFunc(16000);

but it works fine if I call it that

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 possible ...

I understand that there is a stack that overflows, but which stack? How can i fix this?

Thank.

+5
source share
7 answers

The problem is stack overflow.

Why is this happening:

The stack is a special memory area in which several things are stored:

  • ( ) . , , , .

, . , .

:

:

  • , , .
  • (, )
  • .

, - .

+12

, 16000 .

, ! . .

+11

. , , . , , , , , . , , , ( ). . , , .

CheckFunc .

+2

# . , .

, , , , .

0

. 16000 , ( ).

0

.

, ( , , "", "", ), , . , "" .

, - , , .

, 16000 "i" , 16000 , . 1000 .

, -, " ", ; , .

0

- .

, , . , , , .

:

+---------------------+
|                     |
         ...
|                     |
+---------------------+  <-- stack pointer before call
| parameter: int      |
+---------------------+
| return address      |
+---------------------+
| stack frame for     |
|   local variables   |
+---------------------+  <-- stack pointer in the call

, ( 2 IIRC), , , .

, . :

private void CheckFunc(int i) {
  if (i == 0) {
    MessageBox.Show("good");
  } else {
    CheckFunc(i / 2);
  }
}

, 31 .

0

All Articles