I've asked Google and did some research on StackOverflow. My question is that when I enter the main()
function in a C++ program and declare the very first variable, why is it that the address of this variable can vary upon different executions? Please see my example program below:
#include <iostream>
int main() {
int *a = new int;
int *b = new int;
std::cout << "address: " << a << " " << b << std::endl;
std::cout << "address of locals: " << &a << " " << &b << std::endl;
return 0;
}
Result on execution 1:
address: 0xa32010 0xa32030
address of locals: 0x7fff10de2cf0 0x7fff10de2cf8
Result on execution 2:
address: 0x1668010 0x1668030
address of locals: 0x7ffc252ccd90 0x7ffc252ccd98
Result on execution 3:
address: 0x10e0010 0x10e0030
address of locals: 0x7ffd3d2cf7f0 0x7ffd3d2cf7f8
As you can see, I get different results upon different executions. The first line of the output corresponding to the address of the allocated memory, which should happen in the heap – if they are assigned different addresses every time, it kinda make sense to me. However, even when I print the addresses of local variables – corresponding to the second line – the results are still different.
At first glance, I was thinking it's because the program is printing a physical memory address, but this post, Virtual Memory or Physical Memory, disproves my initial thought. Is there any reason that, given the programs’ execution is "the same," with no threading, no user inputs, etc, that there are still memory allocations with different addresses?
Testing environment:
- Linux 14.04
- Mac OS X 10.10