Caveat: alloca
is only mentioned here for the sake of completeness. It is entirely non-portable (not covered by any of the common standards) and has a number of potentially dangerous features that make it un-safe for the unaware. Modern C code should replace it with Variable Length Arrays (VLA).
#include <alloca.h>
// glibc version of stdlib.h include alloca.h by default
void foo(int size) {
char *data = alloca(size);
/*
function body;
*/
// data is automatically freed
}
Allocate memory on the stack frame of the caller, the space referenced by the returned pointer is automatically free'd when the caller function finishes.
While this function is convenient for automatic memory management, be aware that requesting large allocation could cause a stack overflow, and that you cannot use free
with memory allocated with alloca
(which could cause more issue with stack overflow).
For these reason it is not recommended to use alloca
inside a loop nor a recursive function.
And because the memory is free
'd upon function return you cannot return the pointer as a function result (the behavior would be undefined).
malloc
free
,realloc
functions (undefined behavior)malloc()
alloca()
and VLAs (variable length arrays) in a single functionalloca()
is not as portable as malloc()
et alalloca()
in new codeModern alternative.
void foo(int size) {
char data[size];
/*
function body;
*/
// data is automatically freed
}
This works where alloca()
does, and works in places where alloca()
doesn't (inside loops, for example). It does assume either a C99 implementation or a C11 implementation that does not define __STDC_NO_VLA__
.