title: How to realloc based on size of array?
body: <p>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):</p>
  
  <pre><code>#include &lt;stdio.h&gt;
  #include &lt;stdlib.h&gt;
  
  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]&lt;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&gt;size){
                      fibo = (int *) realloc(fibo, (size *= 2)*sizeof(int));
              }
      }
  
      printf("Sum = %d\n", sum);
      return 0;
  
  }
  </code></pre>
  
  <p>Anyone know why realloc is failing, and how I can fix it? </p>