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

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?

closed as off-topic by Doc Brown, gnat, amon, Christophe, Bart van Ingen Schenau Jan 27 at 10:40

This question appears to be off-topic. The users who voted to close gave this specific reason:

  • "Questions asking for assistance in explaining, writing or debugging code are off-topic here. These can be asked on Stack Overflow if they include the desired behavior, a specific problem or error, and the shortest code necessary to reproduce it in the question (see Minimal, Complete, and Verifiable Example)." – gnat, amon, Christophe
If this question can be reworded to fit the rules in the help center, please edit the question.


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.

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