Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why two variables declared one after another are not next to each other in memory?

I am using a code sample to check the distance between two integers like in the answer of this question.

int i = 0, j = 0;
std::cout << &i - &j;

From my understanding of the memory representation, these memory addresses of these two variables should be next to each other and the difference should be exactly 1.

To my surprise, running this code with MS compiler in VS2017 prints 3 and running the same code with GCC prints 1.

Why this happens, is something wrong with VS?

like image 928
meJustAndrew Avatar asked Dec 06 '25 14:12

meJustAndrew


1 Answers

C++ standard does not make any requirements for C++ compilers to allocate variables with automatic storage duration in any particular way, including making them contiguous in memory. In fact, compiler may choose to not allocate any memory to a variable, optimizing it out completely.

That is why subtracting pointers makes sense only when they both point to memory inside the same array, or one element past the end of it. In all other situations, including yours, you get undefined behavior.

like image 193
Sergey Kalinichenko Avatar answered Dec 09 '25 04:12

Sergey Kalinichenko