Tuesday, October 26, 2010


Memory can be allocated off the stack at runtime using alloca().
alloca() is a C extension that allocates memory on the stack, typically by just moving the Stack Pointer down in order to allocate bytes. This can be used to allocate memory in exception-safe way (in some sense).

If an exception occurs, the allocated memory is automatically deallocated when stack frame is popped off the stack.

The second 'a' in 'alloca' stands for auto memory, which is the stack. alloca() is defined in the header file <alloca.h>. A corresponding <calloca> include file does not exist. alloca() is a C Language extension supported by many compilers. It was brought over into C++ on many compilers. It is not mentioned in the C++ standard. It's C++ functionality is implemented by the dynamic array feature. Here is a code example:

    void func(int size)
        char * pMem = static_cast<char*>;(alloca(size));
        cout << "0x" << hex << reinterpret_cast<int>(pMem) << endl;
        #if 1
            char myArray[size];
            char * pMem2 = &myArray[0];
            cout << "0x" << hex << reinterpret_cast<int>(pMem2) << endl;

The code in the #if uses variable length arrays. Variable length arrays were intoduced in C99. Interestingly, alloca() works on g++, Sun C++, and IBM C++. Variable length arrays work on all of the above except Sun C++.

No comments:

Post a Comment