title: To write robust C program, how do you avoid too many different free () combinations?
body: <p>For example,
  I need to malloc two pieces of memory, so:</p>
  
  <pre><code>void *a = malloc (1);
  
  if (!a)
    return -1;
  
  void *b = malloc (1);
  
  if (!b)
  {
    free (a);
    return -1;
  }
  </code></pre>
  
  <p>Notice if the second malloc fails, I have to free "a" first. The problem is, this can be very messy if there are many such malloc's and error checking's, unless I use the notorious "goto" clause and carefully arrange the order of free's along with the labels:</p>
  
  <pre><code>void *a = malloc (1);
  
  if (!a)
    goto X;
  
  void *b = malloc (1);
  
  if (!b)
    goto Y;
  
  return 0; //normal exit
  
  Y:
    free (a);
  X:
    return -1;
  </code></pre>
  
  <p>Do you have any better solution to this situation? Thanks in advance.</p>