One of the pain-points in C is manual memory management. Using C++ with RAAI gives you a better time but it's still a hassle to create the RAAI wrappers.
The Good News
Most programmers are familiar with
malloc() (C++: new), calloc (), and
realloc() all of which require keeping track and
free()/delete-ing the allocated memory. But not everyone has heard of
alloca() which doesn't!
alloca() allocates memory on the
stack instead of the heap. This gives a number of advantages inherent to stack variables:
- No expensive list/tree searches or heap adjustment functions means that
alloca() is very fast.
-
alloca() does not need to perform locking which means that it scales much better than malloc().
- No memory fragmentation
- Nonlocal exits with
setjmp()/longjmp() automatically free the space allocated with alloca().
and
- There is no need to
free()/delete any alloca-ed variables! Yay!
The Bad News
Sadly
alloca() has a terrible flaw - It
doesn't fail!
What this means is that when your application doesn't have enough stack space
alloca() still attempts to return a pointer. On different architectures this has the result of raising segmentation violations, bus errors, or structured exceptions (windows). Not good at all! :-(
Conclusion
Overall
alloca() actually behaves a lot like a
local, variable-size array. And while C99 allows local arrays with variable size, not all compilers support this useful feature.
gcc 3.4.4 seems to allow it while MS
cl 13.10.3077 doesn't.
So consider using
alloca() whenever you need a local, variable sized array and your compiler complains. Basically keep it in your toolbox for the right occasion.