title: How can I correctly handle malloc failure in C, especially when there is more than one malloc?
body: <p>Suppose this is a part of my code:</p>
  
  <pre><code> int foo()
   {  
      char *p, *q ;
      if((p = malloc(BUFSIZ)) == NULL) {
          return ERROR_CODE;
      }
      if((q = malloc(BUFSIZ)) == NULL) {
          free(p)
          return ERROR_CODE;
      }
      /* Do some other work... */
  
      free(p);
      free(q);  
   }
  </code></pre>
  
  <p>Since it's possible that the first <code>malloc</code> is successful but the second one fails, I use <code>free(p)</code> in the second "error handler". But what if there are more <code>malloc</code>'s and what if I want to modify the code (adjusting their orders, adding or deleting some <code>malloc</code>)?</p>
  
  <p>I know in C++ there are things like RAII and exception safe, etc. But in general, what is the correct way to handle <code>malloc</code> failure in C? (maybe using some <code>goto</code>?)</p>