NONPORTABLE nonstandard C function.

void *alloca(size_t size); (assuming it exists) enlarges the current function's stack frame by size bytes and returns a pointer to the start of this block of memory (note that depending on the direction in which the stack grows, this can be based on the value in the stack pointer before or after the stack frame is grown). If the growth of the stack is not permitted by the OS the action is undefined.

Memory allocated by alloca() needn't be freed! It remains allocated until the function exits, at which point it silently vanishes. Think of it as a dynamically-specified run time version of allocation of memory for local (automatic) variables.

Not all architectures and ABIs can support alloca(), and even when it is supported the sizes of blocks which can legally be allocated are highly machine-dependent. It is certainly no part of the ISO C standard. DO NOT USE THIS FUNCTION! The Solaris manpage says this about it:

The alloca() function is machine-, compiler-, and most of all, system-dependent. Its use is strongly discouraged.

Of course, if your function needs to allocate a block of memory and calls functions which could exit via longjmp(), you may have no choice but to use it. Often, however, its use (mostly in older programs) is just due to programmer laziness, or an extreme need for efficient allocation (alloca() is much faster than malloc() and free()!).

A good C++ design will never have any excuse to use alloca(). Instead, judicious use of local objects (combined with the replacement of longjmp() with proper exception handling) ensures allocated memory is correctly freed. You can even get your destructors called during stack unwinding.

But still, nothing can come close to the speed of an alloca() of a small block at the right point in a program...

Log in or register to write something here or to contact authors.