views:

164

answers:

3

I want to allocate memory on the stack.

Heard of _alloca / alloca and I understand that these are compiler-specific stuff, which I don't like.

So, I came-up with my own solution (which might have it's own flaws) and I want you to review/improve it so for once and for all we'll have this code working:

/*#define allocate_on_stack(pointer, size) \
    __asm \
    { \
        mov [pointer], esp; \
        sub esp, [size]; \
    }*/
/*#define deallocate_from_stack(size) \
    __asm \
    { \
        add esp, [size]; \
    }*/

void test()
{
    int buff_size = 4 * 2;
    char *buff = 0;

    __asm
    { // allocate
        mov [buff], esp;
        sub esp, [buff_size];
    }

    // playing with the stack-allocated memory
    for(int i = 0; i < buff_size; i++)
        buff[i] = 0x11;

    __asm
    { // deallocate
        add esp, [buff_size];
    }
}

void main()
{
    __asm int 3h;
    test();
}

Compiled with VC9.

What flaws do you see in it? Me for example, not sure that subtracting from ESP is the solution for "any kind of CPU". Also, I'd like to make the commented-out macros work but for some reason I can't.

+10  A: 

Sorry, but you'd be better off using alloca than doing that kind of stuff. Not only it's x86 specific, but also, it'll probably give unexpected results if compiled with optimizations on.

alloca is supported by many compilers, so you shouldn't be running into problems anytime soon.

JPD002
By way of confirmation I too have yet to use a compiler that doesn't support `alloca`. Some spell it differently, but this can be worked around with `#define`. (That said, whilst I have used a number of compilers, I have certainly not used every single one available.)
brone
+1  A: 

Don't define deallocate_from_stack. As implemented, deallocate_from_stack will likely only do what you expect if called immediately after allocate_from_stack, and maybe even not then. Plus, the whole point of stack allocation is to avoid having to call free or any equivalent.

The allocate macro looks fine to me, though as others have noted it only works on x86 (which makes your concerns about "any kind of CPU" moot).

JSBangs
+3  A: 

Your solution is more platform dependent than alloca (it will not work on x64). There is a standard compliant and pretty fast way for allocating the memory. You could pre-allocate large block of memory and manage memory allocation by yourself. Take a look on Boost Pool Library

Kirill V. Lyadvinsky