문제

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