开发者

Dynamic stack allocation in C++

开发者 https://www.devze.com 2022-12-30 23:24 出处:网络
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.

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) an开发者_如何学运维d 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.


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.


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


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).

0

精彩评论

暂无评论...
验证码 换一张
取 消