title: C API design: what to do when malloc returns NULL?
body: <p>Let's say I'm writing a little library in C -- some data structure, say. What should I do if I'm unable to allocate memory? </p>
  
  <p>It might be pretty important, e.g. I need some memory to initialize the data structure in the first place, or I'm inserting a key-value pair and want to wrap it in a little struct. It could also be less critical, for instance something like a <code>pretty_print</code> function that builds up a nice string representation of the contents. However, it's typically more serious than your average error -- there might not be a point in continuing at all. A ton of sample uses of <code>malloc</code> online just straight up exit the program if it returns <code>NULL</code>. I'm guessing a lot of real client code does that too -- just pop up some error, or write it to <code>stderr</code>, and abort. (And a lot of real code probably doesn't check the return value of <code>malloc</code> at all.) </p>
  
  <p>Sometimes it makes sense to return <code>NULL</code>, but not always. Error codes (or just some boolean <code>success</code> value), either as return values or out parameters work fine, but it seems like they can clutter up or hurt the readability of the API (then again, maybe that's somewhat expected in a language like C?). Another option is to have some sort of internal error state the caller can subsequently query, e.g. with a <code>get_error</code> function, but then you have to be careful about thread safety, and it might be easy to miss; people tend to be lax about checking for errors anyway, and if it's a separate function altogether they might not know about it, or they might not bother (but then I guess that's their problem).</p>
  
  <p>(I've sometimes seen <code>malloc</code> wrapped in a function that just tries again until memory is available...</p>
  
  <pre><code>void *my_malloc(size_t size)
  {
      void *result = NULL;
      while (result == NULL)
          result = malloc(size);
      return result;
  }
  </code></pre>
  
  <p>But that seems kind of silly and maybe dangerous.)</p>
  
  <p>What's a proper way to handle this?</p>