alloca
alloca(n) allocates n bytes on the caller's stack and returns a pointer to them. The storage vanishes when the function returns. There is no free, and there is no portable failure return.
Detailed Explanation
alloca is not in ISO C. It is a common extension (<alloca.h> on some systems, a builtin on GCC and Clang). It grows the stack frame by n bytes and hands you the space. Returning from the function pops the frame, so the pointer dangles automatically. You do not call free. Calling free on an alloca pointer is undefined.
Because it is the stack, large or attacker-controlled n is a stack overflow. Stack overflow is undefined behavior. Unlike malloc, you do not get NULL on a typical implementation; you get a crash or silent corruption. VLAs (int buf[n];) are the standard-C cousin and have the same size risk. Many style guides ban both in library code.
alloca in a loop allocates again each iteration and usually cannot reuse the previous chunk. A loop of alloca calls can blow the stack even when each n is small. Prefer one allocation before the loop, or malloc.
Some implementations are unhappy with alloca after the function has called other functions, or in functions that also use VLAs, or as an argument expression (f(alloca(n))). The safe pattern, if you use it at all, is one alloca at the top of a leaf-ish function with a tiny, trusted n.
Portable code uses malloc and free, or a caller-provided buffer. Embedded code that cannot heap-allocate uses a static buffer or a caller arena. alloca is a last resort for a small, bounded scratch pad when profiling says the heap is the cost — and even then, a large stack array with a compile-time size is clearer.
Code Examples
#include <stdio.h>
#include <string.h>
#if defined(__GNUC__)
#include <alloca.h>
#endif
static void greet(const char *name)
{
size_t n = strlen(name) + 8;
if (n > 64) { /* bound it or do not alloca */
return;
}
char *buf = alloca(n);
snprintf(buf, n, "hi %s", name);
printf("%s\n", buf); /* prints: hi c */
}
int main(void)
{
greet("c");
return 0;
}#include <stdio.h>
#include <stdlib.h>
#include <string.h>
/* Portable replacement: caller sees failure. */
static int greet_malloc(const char *name)
{
size_t n = strlen(name) + 8;
char *buf = malloc(n);
if (buf == NULL) {
return -1;
}
snprintf(buf, n, "hi %s", name);
printf("%s\n", buf);
free(buf);
return 0;
}
int main(void)
{
return greet_malloc("c") == 0 ? 0 : 1;
}Common Gotchas
There is no reliable `NULL` on failure
a huge `n` is a stack overflow, not a handled error.
`alloca` in a loop stacks allocations
the stack grows by `n` each time.
`alloca` is not standard C
VLAs are standard-but-optional; `malloc` is both.
`free(alloca_ptr)` is undefined behavior
`free(alloca_ptr)` is undefined behavior