Find limit of recursion: Difference between revisions

Content added Content deleted
Line 151:
 
Segmentation fault occurs when i is 523756. (This was checked debugging with gdb rather than waiting the output: the printf line for the test was commented). It must be noted that the recursion limit depends on how many parameters are passed onto the stack. E.g. adding a fake double argument to <code>recurse</code>, the limit is reached at <code>i == 261803</code>. The limit depends on the stack size and usage in the function. Even if there are no arguments, the return address for a call to a subroutine is stored on the stack (at least on x86 and many more processors), so this is consumed even if we put arguments into registers.
 
The following code may have some effect unexpected by the unwary:
<lang C>#include <stdio.h>
 
char * base;
void get_diff()
{
char x;
if (base - &x < 200)
printf("%p %d\n", &x, base - &x);
}
 
void recur()
{
get_diff();
recur();
}
 
int main()
{
char v = 32;
printf("pos of v: %p\n", base = &v);
recur();
return 0;
}</lang>
With GCC 4.5, if compiled without -O2, it segfaults quickly; if <code>gcc -O2</code>, crash never happens, because the optimizer noticed the tail recursion in recur() and turned it into a loop!
 
=={{header|COBOL}}==