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.
source
share