Data Stack

This is pretty C specific, but may be useful for C++ as well in some cases.

Data stack makes it very easy to implement functions returning dynamic data but without having to worry much about memory management like freeing the result or having large enough buffers for result.

It's basically a stack with stack frames that you define. Like:

  // allocate memory here
  // they're free'd now

Advantages over control stack (including alloca()):

Advantages over malloc():


The code

data-stack.c, data-stack.h. For more complete sources and use cases see Dovecot (especially the strfuncs.h).

GNU obstack is also a data stack, but I find it's API a bit too bloated and difficult to use.