I am compiling the following code on Mac OS X, using GCC:
using namespace std;
int x;
int& getRef () {
return x;
}
string getName () {
return "Alex";
}
int main() {
int a;
a = 7;
getRef() = 4;
cout << x << ", address: " << &getRef() << endl;
string name = getName();
cout << getName() << ", address: " << &name << endl;
}
The output of this program is:
4, address: 0x10617c0d8
Alex, address: 0x7fff59a851b0
I would like to understand 2 things:
- Why are the values of these 2 variables always stored under the same addresses each time I run this program?
- Why does the
string
have longer address than theint
, is this related to the fact thatgetName()
is an rvalue?
The reason for the seemingly large gap between the addresses of these two variables is the fact that they are allocated in different memory sections within the executable image:
Global variable
x
is allocated in the data-section.Therefore, its address is constant throughout the execution of the program.
Local variable
name
is allocated in the stack.The address of a local variable in a function depends on the state of the stack (the value of the SP register) at the point in execution when the function is called.
In your example, the state of the stack is simply identical each time function
main
is called.But suppose that this variable was declared in a different function:
Now, try to call this function from within different stack depths, and you'll get different addresses: