title: "Invalid read of size 4" when trying to realloc memory
body: <p>I'm writing a Snake game as the first "serious" project in C. But when I try to grow the snake, program crashes with SEGFAULT error.
  So, i tried to run the game in Valgrind, and got this:</p>
  
  <pre><code>==11312== 30 errors in context 7 of 7:
  ==11312== Invalid read of size 4
  ==11312==    at 0x10969E: collide (game.c:238)
  ==11312==    by 0x108FBD: main (game.c:120)
  ==11312==  Address 0x5897c60 is 0 bytes inside a block of size 40 free'd
  ==11312==    at 0x4C31D2F: realloc (in /usr/lib/valgrind/vgpreload_memcheck-amd64-linux.so)
  ==11312==    by 0x109724: snake_grow (game.c:250)
  ==11312==    by 0x108F7D: main (game.c:113)
  ==11312==  Block was alloc'd at
  ==11312==    at 0x4C31B25: calloc (in /usr/lib/valgrind/vgpreload_memcheck-amd64-linux.so)
  ==11312==    by 0x109278: start (game.c:159)
  ==11312==    by 0x108EC0: main (game.c:91)
  ==11312== 
  ==11312== ERROR SUMMARY: 80 errors from 7 contexts (suppressed: 0 from 0)
  </code></pre>
  
  <p>As I can suggest, I did realloc wrong and that is why the game crashes. So, the problem should be here:</p>
  
  <pre class="lang-c prettyprint-override"><code>void snake_grow(snake_t *snake){
    snake-&gt;length++;
    snake-&gt;body = realloc(snake-&gt;body, sizeof(snake-&gt;body[0]) * (snake-&gt;length));
    snake-&gt;end = snake-&gt;body + snake-&gt;length - 1;
    snake-&gt;end-&gt;x = snake-&gt;prev_x;
    snake-&gt;end-&gt;y = snake-&gt;prev_y;
  }
  </code></pre>
  
  <p>Or maybe I just use pointer in fuction wrong?</p>
  
  <pre class="lang-c prettyprint-override"><code>bool collide(snake_t *snake, block map[MAXY][MAXX]){
    bool ret = FALSE;
    if(map[snake-&gt;head-&gt;y][snake-&gt;head-&gt;x].collision == COLLIDABLE){
      ret = TRUE;
    }
    for(int i = 1; i &lt; snake-&gt;length; i++){
      if(snake-&gt;body[i].x == snake-&gt;head-&gt;x){
        if(snake-&gt;body[i].y == snake-&gt;head-&gt;y){
      ret = TRUE;
        }
      }    
    }
    return ret;
  }
  </code></pre>
  
  <p>Strange, but I can't find anything similar to my problem. But maybe I just didn't understand solutions.</p>