1

I have compiled the following simple c++ code:

#include <iostream>

int main(){
 int a = 5;
 int b = 6;
 long c = 7;
 int d = 8; 
 return 0;
}

and here is the assembly:

    pushq   %rbp
    .cfi_def_cfa_offset 16
    .cfi_offset %rbp, -16
    movq    %rsp, %rbp
    .cfi_def_cfa_register %rbp
    xorl    %eax, %eax
    movl    $0, -4(%rbp)
    movl    $5, -8(%rbp)
    movl    $6, -12(%rbp)
    movq    $7, -24(%rbp)
    movl    $8, -28(%rbp)
    popq    %rbp
    retq

All the ints have an allocation of 4 bytes which is normal. The long variable movq $7, -24(%rbp), is getting 12 bytes allocated to it (instead of 8) why is that?

Joe
  • 21
  • 1
  • 1
    A duplicate of https://softwareengineering.stackexchange.com/questions/357233/why-does-a-long-int-take-12-bytes-on-some-machines ? – Alex Jan 28 '19 at 18:30

1 Answers1

7

How many bytes is a long in a 64 bit machine?

Ultimately it is the language implementation that decides these matters, not the CPU instruction set.  For example, for a standards compliant implementation, int could be 32 or 64-bits on a 64-bit processor, or even something radically different, though that would be very unusual.

The long variable movq $7, -24(%rbp), is getting 12 bytes allocated to it (instead of 8) why is that?

It is not that it is getting 12 bytes allocated, but instead that there is a 4 byte hole being skipped between the 8-byte long and the prior 4-byte sized variable.  This 4 byte area is skipped over, because using it for the long variable would mean mis-aligning the long variable.  On the x64 architecture there is a mild penalty for misaligned accesses (though on some other processors (usually RISC-style processors), misaligned accesses fault instead of performance penalty).   The compiler is aware of alignment considerations, so skips some memory in order to store the long more appropriately.

The 4 byte stack space that is skipped over is virtually free, so this is a good speed-space trade off.  One could argue that this is a poor trade off within a potentially huge number of heap based objects, but not in the stack for local variables.

Erik Eidt
  • 33,282
  • 5
  • 57
  • 91