如何通过地址更改const变量的值? [重复]

时间:2022-06-08 23:42:11

This question already has an answer here:

这个问题在这里已有答案:

I'm trying to change value of const variable via its address.

我试图通过其地址更改const变量的值。

following this code:

遵循以下代码:

#include <iostream>
#include <string>
#include <stdlib.h>
#include <stdint.h>
#include <time.h>
#include <stdio.h>

using namespace std;

int main(void)
{
    uint64_t const x = -1;
    uint64_t *b = reinterpret_cast<uint64_t*>(0x28ff10);
    cout<< x << endl;
    cout<< &x << " " << b << " " << *b << endl;
    printf("%p\n", &x);
    *b = 10;
    cout<< &x << " " << x << " " << b << " " << *b << " " << *(reinterpret_cast<uint64_t*>(0x28ff10)) <<endl;
    return 0;
}

Compiled with MinGW 4.8.1:

使用MinGW 4.8.1编译:

g++ -g main.cpp && ./a.exe

g ++ -g main.cpp && ./a.exe

And this is output:

这是输出:

18446744073709551615
0x28ff10 0x28ff10 18446744073709551615
0028FF10
0x28ff10 18446744073709551615 0x28ff10 10 10

Could anyone explain it ?

谁能解释一下呢?

EDIT: Figured out! compile still optimized my variable although I compiled it with -O0. Looked at ASM generated, I saw that printf and cout put directly the value instead of the variable symbol.

编辑:想通了!编译仍然优化我的变量虽然我用-O0编译它。看着生成的ASM,我看到printf和cout直接放入值而不是变量符号。

So, to make my code do right behavior, I have to declared it with volatile static

因此,为了使我的代码做正确的行为,我必须用volatile静态声明它

1 个解决方案

#1


I'm trying to change value of const variable via its address.

我试图通过其地址更改const变量的值。

You've already gone wrong by this point.

到目前为止你已经出了问题。

const is short for "constant".

const是“常数”的缩写。

You cannot mutate a constant.

你不能改变常数。

Sometimes you can get it to sort of look like you did, but doing so has undefined behaviour. You told your compiler that it can make all sorts of assumptions about x (including optimising it out from your binary entirely!) because you promise that you'll never change it. Then you change it.

有时你可以让它看起来像你做的那样,但这样做有未定义的行为。你告诉你的编译器它可以做出关于x的各种假设(包括完全从你的二进制文件中优化它!),因为你保证你永远不会改变它。然后你改变它。

No dinner for you tonight, says Mr. Compiler!

Compiler先生说,今晚没有晚餐给你!

#1


I'm trying to change value of const variable via its address.

我试图通过其地址更改const变量的值。

You've already gone wrong by this point.

到目前为止你已经出了问题。

const is short for "constant".

const是“常数”的缩写。

You cannot mutate a constant.

你不能改变常数。

Sometimes you can get it to sort of look like you did, but doing so has undefined behaviour. You told your compiler that it can make all sorts of assumptions about x (including optimising it out from your binary entirely!) because you promise that you'll never change it. Then you change it.

有时你可以让它看起来像你做的那样,但这样做有未定义的行为。你告诉你的编译器它可以做出关于x的各种假设(包括完全从你的二进制文件中优化它!),因为你保证你永远不会改变它。然后你改变它。

No dinner for you tonight, says Mr. Compiler!

Compiler先生说,今晚没有晚餐给你!