title: Freeing dynamic 2D array not working as expected in C
body: <p>When I run code like the following:</p>
  
  <pre><code>#include &lt;stdio.h&gt;
  #include &lt;stdlib.h&gt;
  
  int main (void)
  {
      int i, count = 0x09;
      int sizei = 5, sizej = 2;
  
      int **ary = malloc (sizei * sizeof **ary);
      for (i = 0; i &lt; sizei; i++) {
          *(ary + i) = malloc (sizej * sizeof *(ary + i));
          **(ary + i) = ++count;
          printf (" %2d |%p| +%x+ \n", i, (ary + i), *(*(ary + i)));
      }
  
      puts("----");
      for (i = sizei - 1; i &gt;= 0; i--) {
          printf (" %2d |%p| +%x+ \n", i, (ary + i), *(*(ary + i)));
          free (*(ary + i));   
      }
      puts("----");
  
      free (ary);
      return 0;
  }
  </code></pre>
  
  <p>I would expect that the first half would create a 2d dynamic array of ints called <code>ary</code> (i.e a pointer to a dynamically allocated array of pointers, each pointing to a dynamically allocated array of ints). The 0th element of each array <code>**(ary + i)</code> would then be recursively assigned the current value of <code>count</code>.</p>
  
  <p>The second half would iterate in reverse, freeing each element of <code>ary</code> in the reverse it was malloc'd, followed by freeing <code>ary</code> itself.</p>
  
  <p>This appears to work fine until I try to free <code>*(ary + 0)</code>, at which point I get a double free / corruption error. I've included the output.</p>
  
  <pre><code>  0 |0x1d6f010| +a+ 
    1 |0x1d6f018| +b+ 
    2 |0x1d6f020| +c+ 
    3 |0x1d6f028| +d+ 
    4 |0x1d6f030| +e+ 
  ----
    4 |0x1d6f030| +e+ 
    3 |0x1d6f028| +d+ 
    2 |0x1d6f020| +c+ 
    1 |0x1d6f018| +b+ 
    0 |0x1d6f010| +1d6f0b0+ 
  *** Error in `./a.out': double free or corruption (out): 0x0000000001d6f030 ***
  </code></pre>
  
  <p>I'm curious why the 0th element of the 0th element of <code>ary</code> (i.e <code>*(*(ary + 0) + 0))</code> or just <code>**ary</code>) became what looks like some memory address (only slighly) out of bounds from what's taken up by this 2d array once it got out of the first loop.</p>
  
  <p>And if I get rid of the second loop and just try to free <code>ary</code> directly without first freeing any of its elements I get something like:</p>
  
  <pre><code>  0 |0x1d6f010| +a+ 
    1 |0x1d6f018| +b+ 
    2 |0x1d6f020| +c+ 
    3 |0x1d6f028| +d+ 
    4 |0x1d6f030| +e+ 
  ----
  *** Error in `./a.out': free(): invalid next size (fast): 0x0000000001d6f010 ***
  </code></pre>
  
  <p>I don't understand what I've done wrong here. Would using array notation make a difference? I need any solutions to allow me to have a dynamic length of each array independant of the length of the rest of the elements of <code>ary</code> if at all possible. The number elements of <code>ary</code> wouldn't necesarily be known at compile time either. I'm using gcc 4.9 if that's relevant.</p>