C ++-什么会影响调用堆栈的顺序?

时间:2019-04-17 03:49:06

标签: c++ callstack

我对调用堆栈的推入和弹出元素的顺序感到困惑。我在static int* ptr中创建并初始化了void first()注意:我知道可能会发生意外情况。但是令我困惑的是,调用堆栈对最近使用的地址的作用。

当程序进入first()级别的函数调用second()时,变量int a位于int x之前的地址。但是在函数int z = 99;中添加行second()之后,变量a仍然停留在指向ptr的地址中。

现在发生了一些奇怪的事情。如果我摆脱了std::cout << " &a = " << &a << std::endl;行,那么*ptr将变为99,这意味着变量z位于x的调试或再次运行位置。

我认为,ptr永远不会放入调用堆栈,因为它是一个静态变量,并且保留在数据段中,这意味着ptr永远不会影响调用堆栈。因此,无论如何,函数second()中的第一个初始化变量将始终位于函数first()中的第一个初始化变量所在的位置。

在这种情况下我迷路了。

没有int z = 99

void first() {
    int x = 7;
    static int* ptr = &x; 
}

void second() {
    int a = 5; // &a = (&x before)
    int b = 1;
    int c = 2;
    int d = 3;
    int e = 4;
    std::cout << " &a = " << &a << std::endl;
    first(); 
}


int main()
{
    first();
    second();
    first();
}

使用int z = 99

void first() {
    int x = 7;
    static int* ptr = &x;
}

void second() {
    int z = 99;
    int a = 5; // &a = (&x before)
    int b = 1;
    int c = 2;
    int d = 3;
    int e = 4;
    std::cout << " &a = " << &a << std::endl;
    first(); 
}


int main()
{
    first();
    second();
    first();
}

没有std::cout语句:

void first() {
    int x = 7;
    static int* ptr = &x;
}

void second() {
    int z = 99; // &z = (&x before)
    int a = 5;
    int b = 1;
    int c = 2;
    int d = 3;
    int e = 4;
    first(); 
}


int main()
{
    first();
    second();
    first();
}

0 个答案:

没有答案
相关问题