How does compiler arrange local variables on stack

2019-07-08 22:35发布

问题:

As we know, local variables is located on stack. However, what is their order? Are they arranged as the order of their declaration? This means that the first declared variable is arrange on the higher address of stack (stack grows to lower address) ? As an example:

void foo(){
 int iArray[4];
 int iVar;
}

On stack, the local variable-- iArray and iVar are arranged as followed?

回答1:

The simplest implementations make it very easy to predict where various variables will end up on the stack. However, those implementations also allow certain security problems (mainly, overflowing a buffer and predicting what the extra data will overwrite, allowing the injection of shellcode).

Since the layout of the stack is implementation defined in most stack-based languages (technically, many such languages don't mandate the use of a stack, but instead have semantics that are easy to implement with a stack), compiler writers have gone to great lengths to make it hard to predict the stack layout at runtime.



回答2:

Only if you have optimisation turned off!

Once the optimiser gets hold of your code all bets are off. Common strategies for aggressive optimisations are:

  • Drop the variable if its never used or is just a copy of another variable.
  • Reorder varaibles in the order they are used. This helps greatly if your app is using swap space and also helps cache utilisation (on some machines).
  • Move often used variables into registers. Common on risk machinces with 32 lovely genreral purpose registers. Not so common on Intel with its measly eight single purpose registers.
  • Change the data type. e.g. casting small ints to intgers often speeds up register loading and caching.
  • reorder storage to minimise slack bytes. eg char a, double b, char c, int d could be reordered to double b, int d, char a, char c thus saving 10 bytes.


回答3:

There is no rule you can depend on. Most compilers will use the declaration order unless you start to optimize the code.

Enabling optimizations can cause reuse of stack space, reordering of local variables or even move the variables to CPU registers, so they don't show up on the stack anymore.

[EDIT] On some systems, the stack grows to bigger addresses. So it starts with 0x1000 and the next address is 0x1001 instead of starting with 0xffff and the next address is 0xfffe.