title: memory management for a dynamically allocated 2D space
body: <p>everyone:
  I just come across an approach to allocate a 2D matrix in C. While practicing it, I'm confused about an unknown bug. </p>
  
  <p>here is the function, first version:</p>
  
  <pre><code>//first version
  static int ** my2DAlloc(int rows, int cols){
      int ** array;
      int * array_head;
      int i;
      int len = sizeof(int*)*rows + sizeof(int)*rows*cols + 1;
      array = (int**)malloc( len );
      memset(array, 0, len);
  
      array_head = (int *) (array + rows);
      for(i=0; i&lt;rows; i++)
          array[i] = array_head + i*cols ;
  
      return array;
  }
  </code></pre>
  
  <p>I don't have any problem with this version. However, I've tried to change the code a little, as the following:</p>
  
  <pre><code>//second version
  static int ** my2DAlloc(int rows, int cols){
      int ** array;
      int * array_head;
      int i;
      int len = sizeof(int*)*rows + sizeof(int)*rows*cols + 1;
      array = (int**)malloc( len );
      memset(array, 0, len);
  
      //array_head = (int *) (array + rows);
      for(i=0; i&lt;rows; i++)
          array[i] = (int *) (array + rows + i*cols);   // &lt;--- the major difference
  
      return array;
  }
  </code></pre>
  
  <p>Regarding this second version, it seems fine to write data to the matrix and read data out. 
  But when I try to free the allocated space, I get system error like: </p>
  
  <pre><code>free(): invalid next size (fast): 0x00000000020df010
  </code></pre>
  
  <p>It seems to be some memory error. But I could not figure out the problem. 
  Could anyone help me out?</p>
  
  <p>Thanks &amp; Regards</p>