Search code examples
cobjective-cobjective-c++alloca

What's the difference between alloca(n) and char x[n]?


What is the difference between

void *bytes = alloca(size);

and

char bytes[size];  //Or to be more precise, char x[size]; void *bytes = x;

...where size is a variable whose value is unknown at compile-time.


Solution

  • alloca() does not reclaim memory until the current function ends, while the variable length array reclaims the memory when the current block ends.

    Put another way:

    void foo()
    {
        size_t size = 42;
        if (size) {
            void *bytes1 = alloca(size);
            char bytes2[size];
        } // bytes2 is deallocated here
    }; //bytes1 is deallocated here
    

    alloca() can be supported (in a fashion) on any C89 compiler, while the variable length array requires a C99 compiler.