Why does my compiler reserve more space than is required for the function stack frame?

I have a function:

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

In the assembly code, in the prolog function:

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

The code needs to reserve space for x ie 4 bytes. But it reserves 16 bytes. Why is this? I have always seen him reserve more space than required.

My guess: it is stored in 16 bytes. those. if I need to say 20 bytes, it will reserve 32 bytes, no matter what.

+6
source share
1 answer

It depends a lot on your architecture and compiler flags, so it’s impossible to point out one thing and say β€œit should be this” here. However, I can give you some pointers that may help you.

First, consider the border of the stack. You may have heard of the -mpreferred-stack-border = X flag for GCC. If not, this basically tells your compiler to have your stack values ​​be 2 ^ X bytes each. Then your compiler will try to optimize your program so that these values ​​match the stack as closely as possible. On the other hand, a GCC modifier, such as __packed__, will cause the compiler to try to set the data on the stack as accurately as possible.

There is also a stack protector. Basically, GCC pushes dummy values ​​onto the stack, which ensures that buffer overflows can do no harm except segfaulting your program (which is not fun, but better than an attacker that controls the instruction pointer). You can easily try this: grab any latest version of GCC and let the user overflow the buffer. You will notice that the program exits with a message in the line "stack detection, termination". Try compiling your program with -fno-stack-protector, and the allocated local memory on the stack is likely to be less.

+5
source

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


All Articles