title: Object creation: Pointer to dynamically allocated data inside a value type object - good or bad?
body: <p>I have a simple struct:</p>
  
  <pre><code>typedef struct {
      int width, height;
      unsigned char *pixels;
  } image;
  </code></pre>
  
  <p>Which one is the better API?</p>
  
  <pre><code>image *imagecreate(int w, int h) {
      image *img = malloc(sizeof(image));
      img-&gt;width = w;
      img-&gt;height = h;
      img-&gt;pixels = calloc(w * h, 3);
      return img;
  }
  
  void imagefree(image *img) {
      free(img-&gt;pixels);
      free(img);
  }
  </code></pre>
  
  <p>or</p>
  
  <pre><code>image imagecreate(int w, int h) {
      image img;  
      img.width = w;
      img.height = h;
      img.pixels = calloc(w * h, 3);
      return img;
  }
  
  void imagefree(image *img) {
      free(img-&gt;pixels);
      img-&gt;width = img-&gt;height = 0;
  }
  </code></pre>
  
  <p>?</p>
  
  <p>It seems to be overkill to do an additional malloc() for such a small struct which is only a wrapper around a pointer to the real dynamically allocated data. But on the other hand it feels unnatural (to me) to hide a pointer to dynamically allocated memory inside a value type. One could think that you don't have to free it.</p>