title: Return a pointer to a dynamically-allocated struct vs. requiring allocated memory from the calling function?
body: <p>In C, it is possible for functions to return pointers to memory that that function dynamically-allocated and require the calling code to free it.  It's also common to require that the calling code supplies a buffer to a second function, which then sets the contents of that buffer.  For example:</p>
  
  <pre><code>struct mystruct {
     int a;
     char *b;
  };
  
  
  struct mystruct *get_a_struct(int a, char*b)
  {
      struct mystruct *m = malloc(sizeof(struct mystruct));
      m-&gt;a = a;
      m-&gt;b = b;
  
      return m;
  }
  
  int init_a_struct(int a, char*b, struct mystruct *s)
  {
      int success = 0;
      if (a &lt; 10) {
          success = 1;
          s-&gt;a = a;
          s-&gt;b = b;
      }
  
      return success;
  }
  </code></pre>
  
  <p>Is one or the other method preferable?  I can think of arguments for both: for the get_a_struct method the calling code is simplified because it only needs to <em>free()</em> the returned struct; for the init_a_struct method there is a very low likelihood that the calling code will fail to <em>free()</em> dynamically-allocated memory since the calling code itself probably allocated it.</p>