title: Unit testing C library, memory management
body: <p>I am working on a quite large C library that doesn't have any tests now. As the API starts to be final, I'd like to start writing unit tests.</p>
  
  <p>Nearly all my functions acts on the first parameter (a structure).</p>
  
  <p>The naive approach to unit test is to have the pre function call structure in a known state, call the function, and then compare the pre call structure with the expected result.</p>
  
  <p>Now this works with structure composed of scalar types, but as for allocated memory, I was wondering what kind of approach you were using.</p>
  
  <p>For example, imagine an image structure, when you do:</p>
  
  <pre><code>CreateImage(&amp;img, x, y);
  </code></pre>
  
  <p>you expect the img->x to be x, img->y to be y and img->pixels to be a pointer to something big enough to hold <code>x * y * sizeof(pixel)</code>.</p>
  
  <p>Checking for the first two is trivial, but what about the img->pixels? I don't mean to check if the malloc call was successful, as I can <a href="https://stackoverflow.com/questions/1711170/unit-testing-for-failed-malloc">overload</a> malloc, but I want to know if malloc was called properly.</p>
  
  <p>This is especially important in case like that:</p>
  
  <pre><code>CreateImage(*img, x, y)
  {
      img-&gt;x = x; img-&gt;y = y;
      /* do something, dhoo, that something is broken and modify x or y */
      img-&gt;pixels = malloc(x * y * sizeof(pixel)); /* wrong allocation size */
      if(!img-&gt;pixels) error("no memory");
  }
  </code></pre>
  
  <p>I hope my question is clear.</p>
  
  <p>Thanks.</p>