Search code examples
c++memoryreference64-bitaddressof

Distance between variables in memory


I wonder how C++ is handling variables so that the distance between the two addresses in memory of integer variables declared and initialized one after another is 3537492 - 3537480 = 12 ( I'm assuming bits(?) )

#include <cstdio>

using namespace std;

int main( int argc, char ** argv )
{
    int x = 1;
    int y = 2;

    printf("int:\t%d\n", sizeof(int));
    printf("unsigned int:\t%d\n", sizeof(unsigned int));

    printf("Address of x\n\tHex:\t%p\n\tDec:\t%d\n", &x, &x);
    printf("Address of y\n\tHex:\t%p\n\tDec:\t%d\n", &y, &y);

    return 0;
}

Output:

int:    4
unsigned int:   4
Address of x
        Hex:    0035FA54
        Dec:    3537492
Address of y
        Hex:    0035FA48
        Dec:    3537480

Solution

  • My guess would be that the compiler is aligning the integers along a word boundary for some performance reason. If a word is 128 bits, or 16 bytes, then such behavior would cause a distance of 12 bytes between variables. You would have to understand a bit more about the architecture you are compiling on to know if I'm right. No pun intended. See http://en.wikipedia.org/wiki/Data_structure_alignment