title: realloc invalid old size
body: <p><em>Disclaimer: This is homework. I am attempting it and do not expect or want anyone to do it for me. Just a few pointers (hehe) where I'm going wrong would be appreciated.</em></p>
  
  <p>The homework requires me to create an <code>int*</code> array that holds 10 elements, and then attempt to insert a million ints into it. Each insertion checks if the array needs to be resized, and if it does, I increase it's size so it can hold one more element.</p>
  
  <p>When I insert 10,000 elements, it works fine, but if I try 100,000 elements, I get the following error:</p>
  
  <pre><code>*** glibc detected *** ./set2: realloc(): invalid old size: 0x00000000024dc010 ***
  </code></pre>
  
  <p>This is the code I'm running. I've commented it so it's easily readable.</p>
  
  <pre><code>void main()
  {
      //begin with a size of 10
      int currentsize = 10;
      int* arr = malloc(currentsize * sizeof(int));       
      int i;
  
      //initalize with all elements set to INT_MAX
      for(i = 0; i &lt; currentsize; i++) {
          arr[i] = INT_MAX;
      }
  
  
      // insert random elements
      for(i = 0; i &lt; 100000; i++) {
          currentsize = add(rand() % 100,arr,currentsize);
      }
  
      free(arr);
  }
  
  /*
      Method resizes array if needed, and returns the new size of the array
      Also inserts the element into the array
  */
  int add(int x, int* arr, int size)
  {
      //find the first available location 
      int newSize = size;
      int i;
      for(i = 0; i &lt; size; i++) {
          if (arr[i] == INT_MAX)
              break;
      }
  
      if (i &gt;= size) {
          //need to realloc
          newSize++;
          arr = realloc(arr, newSize * sizeof(int) );     
      }
  
      arr[i] = x;
  
      return newSize;
  }
  </code></pre>