When 2 ints are stored in Visual Studio, the difference between their locations is 12 bytes. Is there a reason for this?

When I run the following program in VC ++ 2008 Express, I get the difference in location between two sequentially stored integers as "12" instead of the expected "4". In any other compiler, the answer is "4". Is there a special reason why "12"?

#include <iostream> using namespace std; int main() { int num1, num2; cin >> num1 >> num2; cout << &num1 << endl << &num2 << endl; cout << int(&num1) - int(&num2)<<endl; //Here it shows difference as 12. cout << sizeof(num1); //Here it shows the size as 4. return 0; } 
+4
source share
2 answers

I'm going to make a wild guess and say that you built it in debug mode. Try creating it in release mode and see what you get. I know that C ++ runtime puts the memory around the allocated memory in debug mode to catch the buffer overflow. I don't know if it is doing something similar with variables on the stack.

+3
source

You can develop code for a computer in China, or perhaps this is a small and rare flaw in the specific hardware that you use. One old model has difficulty with large numbers, where the upper bits are set, and if the variables are in adjacent memory cells, it was discovered that the accumulation of charge in the main memory can have a cross effect in neighboring memory cells and change the contents. Other options are backup memory cells to detect overflows and overflows, and it may happen that you use 32-bit software mapped to a 48-bit hardware architecture ported to a new model with redundant bits and bytes that remain unused.

0
source

Source: https://habr.com/ru/post/1338450/


All Articles