title: Dynamic 2D Array with realloc gives segmentation fault, but works with malloc
body: <p>I have a problem with my dynamic 2d array. 
  With <code>malloc</code> it worked. With <code>realloc</code>, it failed.</p>
  
  <p>This dosen't work:</p>
  
  <pre><code>#include &lt;stdio.h&gt;
  #include &lt;stdlib.h&gt;
  
  int main(int argc, char *const *argv) {
  
      unsigned ** gmatrix = NULL;
      int cap = 4;
  
      /*
      ...
      */
  
      gmatrix = realloc(gmatrix, 4 * sizeof(unsigned*));
      for(unsigned i = 0; i &lt; cap; i++) {
          gmatrix[i] = realloc(gmatrix, cap* sizeof(unsigned));
      }
      // initialize:
      for(unsigned i = 0; i &lt; cap; i++) {
          for(unsigned j =  0; j &lt; cap; j++) {
              gmatrix[i][j] = 0;
          }
      }
  
  }
  </code></pre>
  
  <p>But this does:</p>
  
  <pre><code>#include &lt;stdio.h&gt;
  #include &lt;stdlib.h&gt;
  
  int main(int argc, char *const *argv) {
  
      unsigned ** gmatrix = NULL;
      int cap = 4;
  
      /*
      ...
      */
      gmatrix = malloc(cap * sizeof(unsigned*));
      for(unsigned i = 0; i &lt; cap; i++) {
          gmatrix[i] = malloc(cap* sizeof(unsigned));
      }
      for(unsigned i = 0; i &lt; cap; i++) {
          for(unsigned j =  0; j &lt; cap; j++) {
              gmatrix[i][j] = 0;
          }
      }
  
  }
  </code></pre>
  
  <p>In the first code part I get a segmentation fault error. Why?</p>