title: Unable to read memory. Can't find what's wrong
body: <p>I've got a piece of code, it's purpose is to draw a background image on one of the game levels. For this purpose I create this structure.</p>
  <pre><code>typedef struct crate_t {
              int x = 0;
              int y = 0;
              int h = 0;
              int w = 0;
              int type = BACKGROUND;
          }crate;
      
  </code></pre>
  <p>Then in the main function I create a 2D array</p>
  <pre><code>crate **Crates = (crate**)malloc(sizeof(crate)*(SCREEN_WIDTH / GrassBlock-&gt;w));
  for (int i = 0; i &lt;= SCREEN_HEIGHT/GrassBlock-&gt;h; i++) {
      Crates[i] = (crate*)malloc(sizeof(crate)*(SCREEN_HEIGHT / GrassBlock-&gt;h));
  }
  </code></pre>
  <p>and I pass it to the function <code>counter = DrawLevelBG(screen, GrassBlock, Border, Crates);</code>. The problem is that the function causes error. &quot;Access violation writing location.&quot; at <code>Obstacles[i][j].x = x;</code></p>
  <pre><code>int DrawLevelBG(SDL_Surface *screen, SDL_Surface *sprite, SDL_Surface *border, crate **Obstacles) {
          int x = 0;
          int y = 0;
          int i = 0;
          int j = 0;
          bool condition = 0;
          while (y &lt; SCREEN_HEIGHT + sprite-&gt;h) {
              DrawSurface(screen, sprite, x + (sprite-&gt;w / 2), y + (sprite-&gt;h / 2));
              if (x &gt;= SCREEN_WIDTH - sprite-&gt;w || x == 0 || y == 0 || y &gt;= SCREEN_HEIGHT - sprite-&gt;h) {
                  DrawSurface(screen, border, x + (sprite-&gt;w / 2), y + (sprite-&gt;h / 2));
                  Obstacles[i][j].x = x;
                  Obstacles[i][j].y = y;
                  Obstacles[i][j].h = border-&gt;h;
                  Obstacles[i][j].w = border-&gt;w;
                  Obstacles[i][j].type = WALL;
                  i++;
                  if (x &gt;= SCREEN_WIDTH - sprite-&gt;w) {
                      y += sprite-&gt;h;
                      x = 0;
                      j++;
                      condition = 1;
                  }
              }
              if (!condition) {
                  x += sprite-&gt;w;
              }
              condition = 0;
          }
          return i;
      }
  </code></pre>
  <p>I know that these ones are caused by pointers not pointing actually to anything but I can't understand what's wrong here. Any help would be greatly appreciated. Thanks.</p>
  <h1>EDIT</h1>
  <p>I've changed my memory allocation piece of code so it looks like that now:</p>
  <pre><code>crate **Crates = (crate**)malloc(sizeof(crate*)*(SCREEN_WIDTH / GrassBlock-&gt;w)*(SCREEN_HEIGHT / GrassBlock-&gt;h));
  for (int i = 0; i &lt;= SCREEN_WIDTH/GrassBlock-&gt;w; i++) {
      Crates[i] = (crate*)malloc(sizeof(crate)*(SCREEN_HEIGHT / GrassBlock-&gt;h));
  }
  </code></pre>
  <p>According to all your replies guys. Unfortunately this doesnt solve the problem. +Important info, the function DrawLevelBG causes ERROR on the first iteration of loop.</p>