尝试在C ++中乱砍一个常量时的奇怪行为 [英] Strange behavior when trying hacking a constant in C++

查看:129
本文介绍了尝试在C ++中乱砍一个常量时的奇怪行为的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述


可能重复:

通过非const指针修改const

Possible Duplicate:
Modifying a const through a non-const pointer

我正在学习C ++,并且非常有趣的指针。我试图改变一个恒定的价值(我的老师叫它后门,请澄清如果我错了)像这样:

I'm studying C++, and very interesting about pointers. And I tried to change value of a constant value (my teacher called it backdoor, please clarify if I'm wrong) like this:

const int i = 0;

const int* pi = &i;

int hackingAddress = (int)pi;
int *hackingPointer = (int*)pi;

*hackingPointer = 1;

cout << "Address:\t" << &i << "\t" << hackingPointer << endl;
cout << "Value:  \t" << i << "\t\t" << *hackingPointer << endl;

system("PAUSE");

return 0;

但是,结果很奇怪。虽然两个地址是相同的,但值是不同的。

However, the result is very strange. Although the two addresses are the same, the values are different.

我的代码是如何执行的? 0 1 的值是什么?

How is my code executed? And where is 0 and 1 value is stored exactly?

推荐答案

您发现了一个C ++开发人员调用未定义的行为的小东西。你告诉编译器 i 是一个值为0的常量。所以,当你问编译器的值 i 时,它告诉你它的值为0.

You've discovered a little thing that C++ developers call undefined behavior. You told the compiler that "i is a constant with the value 0". So when you ask the compiler for the value of i, it tells you that it is 0.

尝试改变常量的值违反了编译器做出的假设(常数将会是,常数),因此,编译器将生成无效或不一致的代码。

Mucking around with trying to change the value of a constant violates the assumptions made by the compiler (that constants are going to be, well, constant), and so, the compiler is going to generate invalid or inconsistent code.

在C ++中有很多情况下可以做一些没有编译器捕获它作为一个错误,但结果是 undefined 。如果你这样做,那么你得到的结果,就像你看到的。编译器做了一些奇怪和意想不到的事情。

There are a lot of situations in C++ where it is possible to do something without the compiler catching it as an error, but the result is undefined. And if you do that, then you get results like what you're seeing. The compiler does something weird and unexpected.

哦,如果你的老师想从这样的例子教你任何

Oh, and if your teacher is trying to teach you anything from an example such as this, he's wrong, and you should be very scared.

只有保证你从这样的代码得到的是:

The only guarantee you get from code like this is this:


编译器可以做任何喜欢的事情

the compiler can do literally anything it likes

,你有一个与编译器的隐式契约:

When you write code, you have an implicit contract with the compiler:

如果我编写良好定义的C ++代码,那么你将它转换成一个可执行文件具有与C ++标准。

"If I write well-defined C++ code, then you convert it into an executable with the same effects as described by the C++ standard".

当你这样做时,你违反了合同。然后编译器也没有义务遵循它。如果给出的编译器代码没有根据C ++标准定义好,那么它不能,并且不会创建一个符合C ++标准指定的可执行文件。

When you do something like this, you violate the contract. And then the compiler isn't obliged to follow it either. If you give the compiler code that is not well-defined according to the C++ standard, then it can't, and isn't going to, create an executable which does as the C++ standard specifies.

这篇关于尝试在C ++中乱砍一个常量时的奇怪行为的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆