Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Dynamic stack allocation in C++

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.

like image 965
Poni Avatar asked Apr 13 '26 17:04

Poni


1 Answers

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.

like image 73
JPD002 Avatar answered Apr 16 '26 07:04

JPD002