Вопрос

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 ?

Это было полезно?

Решение

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.

Другие советы

It's handy when you want to do a dynamic-looking allocation (using e.g. a size that varies at run-time), but still be certain it's all cleaned away once the code that calls alloca() goes out of scope.

Like all automatic ("stack") allocations, it'll hurt your foot if you accidentally store the pointers longer than they're valid.

Лицензировано под: CC-BY-SA с атрибуция
Не связан с StackOverflow
scroll top