Home

alloca

alloca is a function that allocates memory on the calling thread’s stack frame rather than on the heap. The allocated block is automatically reclaimed when the function that called alloca returns, so the programmer does not need to invoke a corresponding free operation. In most C and C++ environments alloca is declared in <alloca.h> or, on some systems, as a built‑in compiler intrinsic, for example __builtin_alloca in GCC and Clang.

Because the memory comes from the stack, allocation and deallocation are fast: the operation typically adjusts

alloca is not part of the ISO C standard and its availability varies across platforms. It is

Security considerations include the risk of stack smashing attacks when large or unchecked allocations are made.

the
stack
pointer.
However,
the
size
of
the
allocation
is
limited
by
the
available
stack
space,
which
can
be
much
smaller
than
the
heap,
and
excessive
use
of
alloca
may
cause
stack
overflow.
The
lifetime
of
the
memory
is
tied
to
the
lexical
scope
of
the
function;
returning
a
pointer
to
the
allocated
block
or
storing
it
in
a
static
or
global
variable
results
in
undefined
behavior.
defined
by
POSIX
only
as
an
optional
extension,
and
many
embedded
or
kernel
environments
omit
it.
Consequently,
portable
code
usually
prefers
heap
allocation
with
malloc/free
or
uses
variable‑length
arrays,
which
are
standard
in
C99
and
later.
Some
compilers
provide
warnings
for
alloca
usage,
and
static
analysis
tools
can
flag
potential
misuse.
When
used
judiciously—typically
for
small,
short‑lived
buffers—alloca
can
improve
performance
and
simplify
memory
management,
but
developers
should
weigh
its
non‑portable
nature
and
stack‑size
limitations
against
alternative
allocation
strategies.