Avoid alloca

suggest change

alloca 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:

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.

Feedback about page:

Feedback:
Optional: your email if you want me to get back to you:



Table Of Contents