alloca allocate memory on stack

suggest change

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).

Manual page

#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).

Summary

Recommendation

Modern 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__.

Feedback about page:

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



Table Of Contents