编译器发生了什么?我不明白

时间:2020-09-15 01:48:10

标签: c++

#include <iostream>
int main(int argc, char *argv[]) {
    int x = 3;
    int y;
    int *px = &x;
    y = *px--;
    *px = 5;
    std::cout << "&x = " << &x << " px = " << px << " &px = " << &px << "&y =" << &y; // strange line
    std::cout << "x = " << x << " y = " << y << std::endl;
    std::cin.get();
}

当我在“奇怪行”中使用&y时,系统打印出x = 3,y = 5,这可以解释,因为在实际的堆栈存储器中,x的地址位于较高的位置,y的地址位于较低的位置(y的地址= x'address-4),因此* px = 5会更改y的值;

但是!当我在“奇怪的行”中使用y而不是&y时,发生了非常奇怪的事情,x = 3且y = 3!发生了什么事?似乎即使我使用“ g ++ -O0”,也没有任何改变,所以这不是编译器的错,那为什么呢? 图片如下:

enter image description here enter image description here enter image description here enter image description here

1 个答案:

答案 0 :(得分:2)

在这一行:

y = *px--;

您正在通过计算无效的指针来调用undefined behaviorpx指向int,并且不能递减。即使px可以递减,也可以取消引用:

*px = 5;

不允许,因为它没有指向有效的内存。

该程序可能根本不执行任何操作,并且至少在语言规则内分析其产生的输出是没有意义的。