title: C API design: Who should allocate?
body: <p>What is the proper/preferred way to allocate memory in a C API?</p>
  
  <p>I can see, at first, two options:</p>
  
  <p>1) Let the caller do all the (outer) memory handling:</p>
  
  <pre><code>myStruct *s = malloc(sizeof(s));
  myStruct_init(s);
  
  myStruct_foo(s);
  
  myStruct_destroy(s);
  free(s);
  </code></pre>
  
  <p>The <code>_init</code> and <code>_destroy</code> functions are necessary since some more memory may be allocated inside, and it must be handled somewhere.</p>
  
  <p>This has the disadvantage of being longer, but also the malloc can be eliminated in some cases (e.g., it can be passed a stack-allocated struct:</p>
  
  <pre><code>int bar() {
      myStruct s;
      myStruct_init(&amp;s);
  
      myStruct_foo(&amp;s);
  
      myStruct_destroy(&amp;s);
  }
  </code></pre>
  
  <p>Also, it's necessary for the caller to know the size of the struct.</p>
  
  <p>2) Hide <code>malloc</code>s in <code>_init</code> and <code>free</code>s in <code>_destroy</code>.</p>
  
  <p>Advantages: shorter code, since the functions are going to be called anyway. Completely opaque structures.</p>
  
  <p>Disadvantages: Can't be passed a struct allocated in a different way.</p>
  
  <pre><code>myStruct *s = myStruct_init();
  
  myStruct_foo(s);
  
  myStruct_destroy(foo);
  </code></pre>
  
  <p>I'm currently leaning for the first case; then again, I don't know about C API design.</p>