Sunday 15 July 2012

c++ - Memory location of string and int objects or lvalues/rvalues -



c++ - Memory location of string and int objects or lvalues/rvalues -

i compiling next code on mac os x, using gcc:

using namespace std; int x; int& getref () { homecoming x; } string getname () { homecoming "alex"; } int main() { int a; = 7; getref() = 4; cout << x << ", address: " << &getref() << endl; string name = getname(); cout << getname() << ", address: " << &name << endl; }

the output of programme is:

4, address: 0x10617c0d8 alex, address: 0x7fff59a851b0

i understand 2 things:

why values of these 2 variables stored under same addresses each time run program? why string have longer address int, related fact getname() rvalue?

the reason seemingly big gap between addresses of these 2 variables fact allocated in different memory sections within executable image:

global variable x allocated in data-section.

therefore, address constant throughout execution of program.

local variable name allocated in stack.

the address of local variable in function depends on state of stack (the value of sp register) @ point in execution when function called.

in example, state of stack identical each time function main called.

but suppose variable declared in different function:

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

now, seek phone call function within different stack depths, , you'll different addresses:

void func2() { func1(); } int main() { func1(); func2(); homecoming 0; }

c++ memory memory-address lvalue rvalue

No comments:

Post a Comment