Search code examples
cdynamic-memory-allocationallocastack-memory

What is the application of alloca?


Possible Duplicate:
In which cases is alloca() useful?

I recently happened to see the use of alloca() function. A google search told me that it's used to allocate space on the stack. I'm not able to grab the application for it ? Also, are there any pitfalls in using this ?


Solution

  • The function alloca was never part of any C standard. It has typically been supplied by vendors as an extension to achieve something like the variable-length arrays ("VLA"s) in C99:

    void foo(int n)
    {
        char arr99[n];            // C99-style VLA
    
        char * p89 = alloca(n);   /* C89 work-around using "alloca" */
    
        // Usage:
        for (int i = 0; i != n; ++i)
        {
            arr99[i] = p89[i] = '0' + i;
        }
    
    }  // memory is freed automatically here
    

    In both cases, the memory is automatically managed and released at the end of the function.

    The use of alloca is mentally burdensome, since it doesn't quite fit the C object model. For example, even if you allocate the memory in a nested scope, it remains live until the end of the enclosing function, not just the block. VLAs have much better semantics, and can be queried with a dynamic sizeof, whereas there is no equivalent mechanism for alloca-allocated memory.