Friday, April 20, 2012

Is there any hard-wired limit on recursion depth in C

The program under discussion attempts to compute sum-of-first-n-natural-numbers using recursion. I know this can be done using a simple formula n*(n+1)/2 but the idea here is to use recursion.



The program is as follows:



#include <stdio.h>

unsigned long int add(unsigned long int n)
{
return (n == 0) ? 0 : n + add(n-1);
}

int main()
{
printf("result : %lu \n", add(1000000));
return 0;
}


The program worked well for n = 100,000 but when the value of n was increased to 1,000,000 it resulted in a Segmentation fault (core dumped)



The following was taken from the gdb message.



Program received signal SIGSEGV, Segmentation fault.
0x00000000004004cc in add (n=Cannot access memory at address 0x7fffff7feff8
) at k.c:4


My question(s):




  1. Is there any hard-wired limit on recursion depth in C? or does the recursion depth depends on the available stack memory?


  2. What are the possible reasons why a program would receive a reSIGSEGV signal?






No comments:

Post a Comment