0

When using Compiler Explorer, I've noticed that the char is always offset by 1 from the previous position. For example:

int main() {
    char a = 1;
    char b = 2;
    char c = 3;
    char d = 4;
    char e = 5;
    return a + b + c + d + e;
}
main:
        ...
        movb    $1, -1(%rbp)
        movb    $2, -2(%rbp)
        movb    $3, -3(%rbp)
        movb    $4, -4(%rbp)
        movb    $5, -5(%rbp)

However, in the following example for a short, why is it offset by 4 and not 2?

int main() {
    char b = 2;
    short c = 2;
    return b;
}
main:
        ...
        movb    $2, -1(%rbp)
        movw    $2, -4(%rbp) <-- why isn't this offset by 2?

I think the answer because since it is two bytes, it needs to fit at memory addresses 3 & 4, so if it were at 2, it would not have enough space with 1 already being occupied, but I'm not too certain. What are the 'rules' for how bytes are padded/at what offset they are added?

Peter Cordes
  • 328,167
  • 45
  • 605
  • 847
David542
  • 104,438
  • 178
  • 489
  • 842
  • 2
    In general they are aligned to their own size. Other than that the compiler is free to arrange them in any order (obviously without overlapping), not necessarily the one you declared them in. Or it may completely optimize away the memory accesses and instead use registers. – Jester Aug 03 '20 at 23:16
  • Correct, if it was at `-2`, the `short` would overlap with the `char` at `-1`. GCC could have avoided a gap by putting the `char` at the lower address, but chose not to. There are absolutely zero rules for how compilers have to lay out locals on the stack; there are many instances where GCC leaves extra padding or puts them in a different order than source order (e.g. [Why is my compiler reserving more space than required for a function stack frame?](https://stackoverflow.com/q/19486515) or [Why does the compiler allocate more than needed in the stack?](https://stackoverflow.com/q/37770751)) – Peter Cordes Aug 03 '20 at 23:21
  • @PeterCordes so would this be an accurate diagram as to how the memory needs to be allocated? https://imgur.com/a/7FYg2Ai. The memory address offset given is the "most negative" memory byte? – David542 Aug 03 '20 at 23:31
  • 2
    That is **one possibility** and the one that matches the assembly code, yes. It could be allocated in other ways too. – Jester Aug 03 '20 at 23:38

0 Answers0