alloca —
memory allocator
#include
<stdlib.h>
void *
alloca(size_t
size);
The
alloca()
function or macro allocates size bytes of space in the
stack frame of the caller. This temporary space is automatically freed on
return.
alloca() returns a pointer to the
beginning of the allocated space.
alloca() appeared in
Version 7 AT&T UNIX/32V.
alloca() is machine and compiler
dependent; its use is discouraged.
alloca() is slightly unsafe because it
cannot ensure that the pointer returned points to a valid and usable block
of memory. The allocation made may exceed the bounds of the stack, or even
go further into other objects in memory, and
alloca() cannot determine such an error. Avoid
alloca() with large unbounded allocations.
The use of C99 variable-length arrays and
alloca() in the same function will cause the
lifetime of alloca()'s storage to be limited to the
block containing the alloca(). For example, in the
following snippet, p's lifetime does not extend
outside of the block, whereas it would've if vla
hadn't been defined or had been defined as a fixed-length array:
char *p;
{
const int n = 100;
int vla[n];
p = alloca(32);
strcpy(p, "Hello, world!");
printf("Inside: %s\n", p); /* Valid. */
}
printf("Outside: %s\n", p); /* Undefined. */