Why is my compiler reserving more space than required for a function stack frame?

廉价感情. 提交于 2019-12-12 07:56:12

问题


I have a function:

void func(int a)
{
    int x = a+2;
}

In the assembly code, in function prolog:

push %ebp
mov %esp, %ebp
sub $0x10, %esp

The code only needs to reserve space for x i.e. 4 bytes. But it is reserving 16 bytes. Why is that ? I have always seen it to reserve more space than required.

My guess: it tends to store in 16 bytes. i.e. if I needed say 20 bytes, it will reserve 32 bytes, no matter what.


回答1:


This highly depends on your architecture and compiler flags, so it is impossible to point to a single thing and say "this must be it" here. However, I can give you some pointers you may find helpful.

First, consider the stack boundary. You may have heard of the -mpreferred-stack-boundary=X flag to GCC. If not, it basically tells your compiler to prefer your values on the stack to be 2^X bytes each. Your compiler will then try to optimize your program so that these values fit on the stack as best as possible. On the other hand, GCC modifier such as __packed__ will make the compiler try to fit the data in the stack as tightly as possible.

There's also the stack protector. Basically, GCC places dummy values on the stack that make sure buffer overflows can't any harm other than segfaulting your program (which isn't fun, but better than an attacker tacking control of the instruction pointer). You can easily try this out: take any recent version of GCC and let the user overflow a buffer. You'll note that the program exits with a message along the lines of 'stack smashing detected, terminated'. Try compiling your program with -fno-stack-protector, and the allocated local memory on the stack will probably be smaller.



来源:https://stackoverflow.com/questions/19486515/why-is-my-compiler-reserving-more-space-than-required-for-a-function-stack-frame

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!