title: Adding an int member to a C struct causes a segfault
body: <p>I'm still learning C, and have started using it to generate images. I can't figure out why one of my programs is segfaulting. Here's the source code, cut down to 40 lines:</p>
  
  <pre><code>#include &lt;stdio.h&gt;
  #include &lt;stdlib.h&gt;
  struct color {
          unsigned char r, g, b;
  };
  struct image {
          int w, h/*, o*/;
          struct color **data;
  };
  int main() {
          // Declarations
          int x, y;
          struct color *black;
          struct image *img;
          // Set up color black
          black = (struct color *) malloc(sizeof(struct color *));
          black-&gt;r = 0;
          black-&gt;g = 0;
          black-&gt;b = 0;
          // Set up image img
          img = (struct image *) malloc(sizeof(struct image *));
          img-&gt;w = 1;
          img-&gt;h = 1;
          /*img-&gt;o = 0;*/
          img-&gt;data = (struct color **) malloc(img-&gt;h * sizeof(struct color *));
          for (y = 0; y &lt; img-&gt;h; y++) {
                  img-&gt;data[y] = (struct color *) malloc(img-&gt;w * sizeof(struct color));
          }
          // Fill in img with black
          for (x = 0; x &lt; img-&gt;w; x++) {
                  for (y = 0; y &lt; img-&gt;h; y++) {
                          img-&gt;data[y][x].r = black-&gt;r;
                          img-&gt;data[y][x].g = black-&gt;g;
                          img-&gt;data[y][x].b = black-&gt;b;
                  }
          }
          // Free black
          free(black);
          // Free img
          for (y = 0; y &lt; img-&gt;h; y++)
                  free(img-&gt;data[y]);
          free(img-&gt;data); // Segfaults
          free(img); // Also segfaults
          return 0;
  }
  </code></pre>
  
  <p>It compiles and runs fine (using gcc on Ubuntu and on Vista with Cygwin), but uncommenting the two lines dealing with img-&gt;o breaks it. I have a feeling it's related to <a href="https://stackoverflow.com/questions/433700/segfault-from-adding-a-variable">this previous question</a>, but I'm malloc'ing everything that needs to be malloc'ed (I think). Any help would be appreciated.</p>