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?
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 togo()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.