title: How to avoid long chain of free's (or deletes) after every error check in C?
body: <p>Suppose I write my code very defensively and always check the return types from all the functions that I call.</p>
  
  <p>So I go like:</p>
  
  <pre><code>char* function() {
      char* mem = get_memory(100);  // first allocation
      if (!mem) return NULL;
  
      struct binder* b = get_binder('regular binder');  // second allocation
      if (!b) {
          free(mem);
          return NULL;
      }
  
      struct file* f = mk_file();  // third allocation
      if (!f) {
          free(mem);
          free_binder(b);
          return NULL;
      }
  
      // ...
  }
  </code></pre>
  
  <p>Notice how quickly <code>free()</code> things get out of control. If some of the function fails, I have to free every single allocation before. The code quickly becomes ugly and all I do is copy paste everything over. I become a copy/paste programmer, even worse, if someone adds a statement somewhere in between, he has to modify all the code below to call the <code>free()</code> for his addition.</p>
  
  <p>How do experienced C programmers go about this problem? I can't figure anything out.</p>
  
  <p>Thanks, Boda Cydo.</p>