1

I wrote the following small C program and you can also see the stack in the screenshot.C stack My question is twofold:

  1. How come there are entire rows of other data between the 3 stack strings?
  2. Why is my first stack string actually on top of the stack? I would think if I had 3 stack strings in succession, the string coming first in the C program would be at the bottom of the stack, and the last string pushed would be at the top.

1 Answer 1

2

How come there are entire rows of other data between the 3 stack strings?

First of all, in x64 Linux code, the stack should be aligned to 16 bytes before any function call, so you can expect that rsp will be aligned as such in compiler generated code.

Now, it's just a compiler's decision how many bytes it will use for item allocation. In GCC, for instance, you can set the alignment of stack items to any power n of 2, using -mpreferred-stack-boundary=n option, according to accepted answer.

Why is my first stack string actually on top of the stack? I would think if I had 3 stack strings in succession, the string coming first in the C program would be at the bottom of the stack, and the last string pushed would be at the top.

Again, it's a compiler's decision how it will organise local variables on the stack as long as it produces code compliant with C standard. I agree, that the natural way is to put the arguments in order of declarations on the stack, but as you see, you cannot assume this in general. If you want to force this order, you can put them in a struct, according to this answer.

1
  • That makes sense. I actually had a thought after I wrote this that likely the compiler has just reserved all of the stack space ahead of time using for example sub esp, 56 , and then moved the data in there rather than doing push instructions. Still a bit odd that it wouldnt follow normal order, but I forgot that it is welcome to do that.
    – the_endian
    Apr 17, 2020 at 21:53

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.