我想在堆栈上分配内存。
听说过 _alloca / alloca,我知道这些是编译器特定的东西,我不喜欢。
所以,我想出了我自己的解决方案(可能有它自己的缺陷),我希望你审查/改进它,这样一劳永逸地我们将让这段代码工作:
/*#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();
}
用VC9编译。
你从中看出什么缺陷?例如,我不确定从 ESP 中减去是否是“任何类型的 CPU”的解决方案。另外,我想让注释掉的宏工作,但由于某种原因我不能。