Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Limited recursion in C?

Tags:

c

I ran this program and it output

...

65088
65089
65090

and then it stopped. Windows 7 said a.exe stopped working. Here is the code:

#include <stdio.h>

void go(void);

main()
{
    go();
}

void go(void)
{
    static int i = 0;
    printf("%d\n", i++);
    go();
}

I think this program should keep on printing numbers indefinitely due to recursion, but it stops at 65090! The C code is compiled with gcc. Any ideas?

like image 810
functionptr Avatar asked Jun 24 '11 20:06

functionptr


People also ask

What is the limit on recursion in C?

There is no theoretical limit to recursion depth in C. The only limits are those of your implementation, generally limited stack space. (Note that the C standard doesn't actually require a stack-based implementation.

What is the limit of recursion?

Due to this, the recursion limit of python is usually set to a small value (approx, 10^4). This means that when you provide a large input to the recursive function, you will get an error. This is done to avoid a stack overflow. The Python interpreter limits the recursion limit so that infinite recursions are avoided.

What is infinite recursion in C?

Infinite Recursion occurs when the recursion does not terminate after a finite number of recursive calls. As the base condition is never met, the recursion carries on infinitely.

What are the three types of recursion?

Different types of the recursionTail Recursion. No Tail/ Head Recursion. Linear recursion.


3 Answers

You are going to overflow the stack at some point because each call to go() must push a return address on the stack even though you pass no arguments to the function call. So every call to go() is taking up a pointer-sized block on the stack for that return address. Since the stack has a limited size, that means at some point you're going to run out of space. The C-language does not specify that a tail-call optimization should take place for circumstances like this, although some compilers (like gcc) do offer that option via optimization switches. But that would be something that is compiler-specific, and independent of the language specification.

like image 63
Jason Avatar answered Oct 18 '22 20:10

Jason


It stops because it is overflowing the stack. Once you overflow the stack the results are undefined.

like image 22
cnicutar Avatar answered Oct 18 '22 20:10

cnicutar


You cannot recurse infinitely on a machine with finite resources -- specifically, the stack. Each nested subroutine call required more stack space, and eventually you will run out.

like image 7
mah Avatar answered Oct 18 '22 21:10

mah