Darryl Gove's blog
Reserving temporary memory using alloca
There are occasions where it's useful to allocate a small temporary working area for the duration of a call to a routine - for example to hold an array. One way of doing this is to use malloc and free:
void f(int a)
{
int* array=(int*)malloc(sizeof(int)*a);
...
free(array);
}
Obviously the use of malloc and free does incur some overhead, and which is undesirable, particularly if this is a performance critical routine.
An alternative approach is to use alloca which allocates memory on the stack, here's the man page. Being on the stack, the memory is 'freed' when the routine exits. Well, the memory isn't allocated, so it's not really freed, but accesses to the memory once the routine exits are not valid - you'll be accessing data either beyond the stack, or in the stack frame of another routine. Neither situation is likely to be good.
The equivalent code is:
#includevoid f(int a) { int* array=(int*)alloca(sizeof(int)*a); ... }
For routines which do require temporary storage, this can be a much faster way of allocating it.
Posted at 01:54PM May 22, 2008 by Darryl Gove in Sun | Comments[2]



Note that with C99 you could use variable length arrays instead, e.g.
void f(int a)
{
int array[a];
}
Posted by Christof Meerwald on May 22, 2008 at 02:36 PM PDT #
Yes. Frank Hofmann also talks about this option:
http://blogs.sun.com/ambiguous/entry/more_on_alloca
The underlying mechanism for alloca and variable length arrays is the same - they both shift the stack pointer.
Posted by Darryl Gove on May 22, 2008 at 02:51 PM PDT #