Dynamic stack allocation in C ++

I want to allocate memory on the stack.

I heard about _alloca / alloca, and I understand that this is a compiler that I don't like.

So, I came up with my own solution (which may have its flaws), and I want you to review / improve it, so that once and for all we will have this code:

/*#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 disadvantages do you see in it? For example, I'm not sure if subtracting from ESP is a solution for "any type of processor." In addition, I would like to make comment macros work, but for some reason I cannot.

+3
source share
3 answers

, alloca, . x86, , , .

alloca , .

+8

, alloca ( x64). . . Boost Pool Library

+3

deallocate_from_stack. , deallocate_from_stack , , allocate_from_stack, , , . , , free .

The highlight macro stands out to me well, although, as others have noted, it only works on x86 (which causes concern about "any kind of processor").

+1
source

Source: https://habr.com/ru/post/1746573/


All Articles