Avoid alloca
suggest changealloca is not part of ISO C. Where an implementation provides it, it allocates storage associated with the current function invocation and releases that storage automatically when the function returns.
It has important drawbacks:
- failure usually cannot be detected portably;
- a large request can exhaust limited stack space;
- repeated calls in a loop can accumulate storage until the function returns;
- the storage cannot be passed to
freeorrealloc; - a pointer to it becomes invalid when the function returns;
- availability, headers, and exact behavior vary by implementation.
Variable-length arrays have some similar lifetime convenience but do not solve unbounded stack use. VLA support also varies by language version and implementation.
For small arrays with a compile-time bound, use an ordinary automatic array. For a run-time or potentially large size, use checked dynamic allocation:
void process(size_t size)
{
unsigned char *data = malloc(size);
if (data == NULL && size != 0) {
/* Handle allocation failure. */
return;
}
/* Use data. */
free(data);
}
Do not introduce alloca into portable new code.
Found a mistake? Have a question or improvement idea?
Let me know.
Table Of Contents