C Language alloca: allocate memory on stack


Example

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

  • call identical to malloc
  • automatically free'd upon function return
  • incompatible with free,realloc functions (undefined behavior)
  • pointer cannot be returned as a function result (undefined behavior)
  • allocation size limited by stack space, which (on most machines) is a lot smaller than the heap space available for use by malloc()
  • avoid using alloca() and VLAs (variable length arrays) in a single function
  • alloca() is not as portable as malloc() et al

Recommendation

  • Do not use alloca() in new code
C99

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