Hello. I delve into the code with the help of a debugger, and try to understand by what principle GCC (C-compiler) places variables (local) on the stack. At first I thought that he pushes them in the same order:

enter image description here

that is, I met int auth_flag and pushes it onto the stack, the variable accordingly receives a larger address (since the stack grows in the direction of the lower addresses). Then password_buffer already gets the address less. But when I changed their places - nothing has changed:

enter image description here

auth_flag still gets the address more and (i.e., it is lower on the stack than password_buffer). I would think that this is how it should be, but I took this example from the book, and there, when the author swaps variables, they switch places and on the stack. Book for 2010, x32 architecture, possibly GCC younger.

Explain why this is happening, why the compiler does not allow you to choose the order of variables themselves, and how it “guides” when it allocates variables.

GCC version: 4.9.2

  • 2
    Do you pass variables by reference? (hint of the type show the source, not screenshots) - strangeqargo
  • 2
    The compiler has the right not to place the variable on the stack at all, but to put it into a register. Or combine several variables into one. Or decompose one variable in several places. C is not an assembler, the compiler is not at all obliged to compile mechanically following what you wrote. - VladD

1 answer 1

Look at it from the other side. If the compiler swaps these two variables on the stack, will it somehow affect your code? The answer is most likely you will not even know about it. And if this is the case, then the compiler can place variables on the stack as it seems to him to be correct. And these rules are sometimes so complex that only developers of the compiler and the processor can argue them.

But there are cases when the compiler can rearrange even more cunning. For example, in the so-called RVO . If an object is created in a function and it is returned from it, the compiler can see it and create an object on the stack of the calling function. Thus, saving the call to the copy constructor and destructor.

But back to the question, why does the compiler rearrange variables? It can set variables in such a way that they are aligned along the 16-byte boundary, thus accelerating.