Under Linux start with
ulimit -s 1024
to limit the stack size.
First of all a program which works:
#include <stdio.h>
static int calc(int c,int *array)
{
if (array!=NULL) {
if (c<=0) {
array[0]=1;
return 1;
}
calc(c-1,array);
array[c]=array[c-1]+3;
return array[c];
} else {
int a[2500+c];
calc(c-1,a);
a[c]=a[c-1]+3;
return a[c];
}
}
int main()
{
int result;
result = calc(1000,NULL);
printf("result = %d\n",result);
}
Now if I change int a[2500+c];
to int a[2500];
then the program crashes with a stack overflow (segmentation fault).
I tried this with
- gcc-4.4.7 -O0, gcc-4.4.7 -O2, gcc-4.4.7 -O3
- gcc-4.8.4 -O0, gcc-4.8.4 -O2, gcc-4.8.4 -O3
- gcc-4.9.3 -O0, gcc-4.9.3 -O2, gcc-4.9.3 -O3
If I use
ulimit -s 1024
then the version with int a[2500];
crashes, whereas the version with int a[2500+c];
works.
Why does the version of the program which uses a variable length array (int a[2500+c];
) consume less stack space than the version which uses a fixed length array (int a[2500];
) ?