A C program is like a fast dance on a newly waxed dance floor by people carrying razors. - Waldi Ravens

the brown-dragon blog

Freedom from free()!

2009-01-15

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:

and 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.

Other Posts

(ordered by Tags then Date)