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:
t_push();
// allocate memory here
t_pop();
// they're free'd now
Advantages over control stack (including alloca()):
- Functions can return a value allocated from data stack
- We can portably specify how much data we want to allocate at runtime
Advantages over malloc():
- FAST, most of the time allocating memory mean only updating a couple of
pointers and integers. Freeing the memory all at once also is a fast
operation.
- No need to free() each allocation resulting in prettier code
- No memory leaks
- No memory fragmentation
Disadvantages:
- Allocating memory inside loops can accidentally allocate a lot of memory
if the loops are long and you forgot to place t_push() and t_pop()
there.
- t_malloc()ed data could be accidentally stored into permanent location
and accessed after it's already been free'd. const'ing the return values
helps for most uses though (see the t_malloc() description).
- Debugging invalid memory usage requires recompilation with
-DDISABLE_DATA_STACK which then uses malloc() and free() for all
allocations and keeping track of them for stack frames making it much
slower.
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.