title: Pointer being freed was not allocated for array of strings in C
body: <p>I know that this question exists in other places like: </p>
  
  <p><a href="https://stackoverflow.com/questions/38540414/pointer-being-freed-was-not-allocated-in-c">pointer being freed was not allocated in C</a>
  <a href="https://stackoverflow.com/questions/3487870/error-pointer-being-freed-was-not-allocated">error: pointer being freed was not allocated</a></p>
  
  <p>but, I'm still very confused. Errors seem to be associated with things like "modifying the original pointer returned by malloc" and "failing to malloc before freeing". I just don't see how these reasons apply to my program. </p>
  
  <p>I'm writing a dynamically allocated array of strings: </p>
  
  <pre><code>#include &lt;stdio.h&gt;
  #include &lt;stdlib.h&gt;
  
  #define NLETTERS 25
  
  typedef struct {
      char** array;
      size_t used;
      size_t size;
  } array_t;
  
  array_t* initArray(size_t initialSize) {
      array_t* a = malloc(sizeof(array_t));
      a-&gt;array = malloc(initialSize*sizeof(char*));
      a-&gt;used = 0;
      a-&gt;size = initialSize;
  
      int i;
      for(i = 0; i &lt; initialSize; i++) {
          a-&gt;array[i] = malloc(sizeof(char) * NLETTERS);
      }
  
      return a;
  }
  
  void insertArray(array_t *a, char* element) {
      if (a-&gt;used == a-&gt;size) {
          a-&gt;size *= 2;
  
          a-&gt;array = realloc(a-&gt;array, a-&gt;size * sizeof(char*));
  
          int i;
          for(i = (int)a-&gt;used; i &lt; a-&gt;size; i++) {
              a-&gt;array[i] = malloc(sizeof(char) * NLETTERS);
          }
      }
      a-&gt;array[a-&gt;used++] = element;
  }
  
  void freeArray(array_t *a) {
      int i;
      for(i = 0; i &lt; a-&gt;size; i++) {
          free(a-&gt;array[i]);
      }
  
      free(a-&gt;array);
      free(a);
      a-&gt;array = NULL;
      a-&gt;used = a-&gt;size = 0;
  }
  
  void print_array(array_t *a) {
      int i;
      for(i = 0; i &lt; a-&gt;size; i++) {
          printf("%s\n", a-&gt;array[i]);
      }
  }
  
  int main(int argc, const char * argv[]) {
      array_t *a;
      a = initArray(2);
      insertArray(a, "hello");
      insertArray(a, "how are you");
      print_array(a);
      insertArray(a, "yup");
      insertArray(a, "you know it");
      print_array(a);
  
      freeArray(a);
  
      return 0;
  }
  </code></pre>
  
  <p>When I attempt to "free", I get the error: "pointer being freed was not allocated" 
  right at </p>
  
  <pre><code>free(a-&gt;array[0]) 
  </code></pre>
  
  <p>in the first iteration of the for-loop in freeArray();</p>
  
  <p>Help would be greatly appreciated. </p>