Stack overflow caused by recursive function

As an aspiring C ++ programmer and computer systems architecture, I am still learning the basics of C ++. Yesterday I read about a recursive function, so I decided to write my own, here is what I wrote: (very simple)

int returnZero(int anyNumber) {
    if(anyNumber == 0)
        return 0;
    else  {
        anyNumber--;
        return returnZero(anyNumber);
    }

}

And when I do this: int zero1 = returnZero (4793); however, this leads to a stack overflow; however, if I pass the value 4792 as a parameter, overflow will not occur.

Any ideas as to why?

+5
source share
6 answers

Whenever you call a function, including recursively, the return address and often arguments are pushed onto the call stack. The stack is finite, so if the recursion is too deep, you will end up stack space eventually.

, , 4793 . . , ~ 100 , .

. Unix ulimit -s.

, tail-recursive, , . : gcc 4.7.2 :

int returnZero(int anyNumber) {
  return 0;
}

:

_returnZero:
        xorl    %eax, %eax
        ret

.

+18

, . - , 4793 .

+1

, , 4793 , , 4792 . , , .

, .

+1

: , , , 4792 - . , . , . , "". .

0

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

If you add another variable, tell int x[10];your function, which calls your recursive function, the number needed to break it will change (probably about 5 or so).

Compile it with another compiler (or even with different compiler settings, for example, with optimization enabled), and it will probably change again.

0
source

Using recursion, you can achieve SuperDigit:

public class SuperDigit
{
    static int sum = 0;

    int main()
    {
        int n = 8596854;
        cout<<getSum(n);
    }

    int getSum(int n){
        sum=0;
        while (n > 0) {
            int rem;
            rem = n % 10;
            sum = sum + rem;
            n = n / 10;
            getSum(n);
        }
        return sum;
    }
}
0
source

All Articles