1

As far as I know is that when I declare an integer type of variable in c++, 4 bytes of memory is allocated by OS (windows).

For testing, I have declared two int type variables (a and b) in main function and compared their memory addresses. I found out that gap between two variable's addresses were 12 bytes. (I was expecting 4 bytes of difference)

below is an simple testing code.

int main()
{   
    int a;
    int b;

    std::cout << &a << std::endl;
    std::cout << &b << std::endl;

    return 0;
}

Output: 007BFDF4 007BFDE8

as shown, gap between two addresses are 12. (I got expected memory addresses when I used arrays) Is this because of byte padding? or any other reason?

ps. I tested this on visual studio 2019 / windows 10.

NikGon
  • 21
  • 1
  • 5
    An implementation is free to organise usage of memory and other resources, including locations of variables in memory, in any way it likes. If you need a guarantee, for some reason, that two `int`s have no "gap" between them, then create an array with two elements. – Peter Feb 17 '20 at 09:46
  • i would run the same program but with pragma pack, arrays obligates the compiler to be linear, it is not Inevitable that the compiler is trying to optimize your code – shimon Feb 17 '20 at 09:50
  • BTW: Here the OS is not involved because this vars are on the stack. – Klaus Feb 17 '20 at 09:55
  • Does this answer your question? [what is "stack alignment"?](https://stackoverflow.com/questions/672461/what-is-stack-alignment) – Botje Feb 17 '20 at 10:18
  • Try it with more variables, like 10. – user253751 Feb 17 '20 at 11:45

0 Answers0