Say you malloc enough memory space to hold an array of size 20. The program is running and now I need enough memory for an array of size say 40. I tried to do this using realloc but it doesn't seem to be working. My code is the following(I'm trying to find the sum of all even-valued fibonacci terms below 4million):
#include <stdio.h>
#include <stdlib.h>
int main(int argc, char** argv){
int i,sum,size;
int *fibo;
size = 20; //initial size of array
fibo = (int *) malloc(size*sizeof(int));
fibo[0]=1;
fibo[1]=1;
i=2;
sum=0;
while(fibo[i-1]<4000000){
fibo[i] = fibo[i-1]+fibo[i-2];
printf("fibo[%d] = %d\n", i, fibo[i]);
if(fibo[i]%2 == 0){
sum+= fibo[i];
}
i++;
if(i>size){
fibo = (int *) realloc(fibo, (size *= 2)*sizeof(int));
}
}
printf("Sum = %d\n", sum);
return 0;
}
Anyone know why realloc is failing, and how I can fix it?