简体   繁体   English

字符串和整数对象或左值/右值的内存位置

[英]Memory location of string and int objects or lvalues/rvalues

I am compiling the following code on Mac OS X, using GCC: 我正在使用GCC在Mac OS X上编译以下代码:

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? 为什么string地址比int ,这是否与getName()是右值这一事实有关?

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 同样0x0001将被截断为0x1

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. 全局变量x在数据部分中分配。

    Therefore, its address is constant throughout the execution of the program. 因此,其地址在整个程序执行期间是恒定的。

  2. Local variable name is allocated in the stack. 局部变量name在堆栈中分配。

    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. 函数中局部变量的地址取决于调用函数时执行时堆栈的状态(SP寄存器的值)。

In your example, the state of the stack is simply identical each time function main is called. 在您的示例中,每次调用函数main时,堆栈的状态都完全相同。

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;
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM