Memory location of string and int objects or lvalues/rvalues

154 views Asked by At

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:

  1. Why are the values of these 2 variables always stored under the same addresses each time I run this program?
  2. Why does the string have longer address than the int, is this related to the fact that getName() is an rvalue?
2

There are 2 answers

0
barak manos On BEST ANSWER

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:

  1. Global variable x is allocated in the data-section.

    Therefore, its address is constant throughout the execution of the program.

  2. 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:

void func1()
{
    string name = getName();
    cout << getName() << ", address: " << &name << endl;
}

Now, try to call this function from within different stack depths, and you'll get different addresses:

void func2()
{
    func1();
}

int main()
{
    func1();
    func2();
    return 0;
}
1
frans On

You're getting the same addresses, because you run the same program in virtual memory. That means that you always have your own address space and there's no reason why to have different behavior in a deterministic run.

Addresses are always the same architecture specific length. The length of the pointer does not say anything about the memory stored there. (otherwise pointer casts would be difficult)

Also 0x0001 will be truncated to 0x1