为什么每次运行此程序时&x都会打印不同的值?
Why &x prints a different value every time I run this program?
#include <iostream>
using namespace std;
int main() {
cout << "Hello, World!" << endl;
int x = 10;
printf("%dn",&x);
printf("%d",x);
return 0;
}
为什么&x
每次运行此程序时都会打印出一个新值?在这种情况下,如何从location_of_x
打印value_of_x
,并将输出值视为10
?
存储器中存储的位置存储了从执行到执行的更改。您应该使用%p(通常用于指针(,而是使用%d(用于整数(显示x的地址,但是这不会改变这样一个事实,即每次启动程序时地址都会有所不同。
如果我没记错的话,随机化是通过地址空间布局随机化完成的,以防止某些类型的利用。
回答您的问题"如何在这种情况下打印*_location_of_x
并将输出视为10
?"请参阅以下内容:
#include <stdio.h> // If you use printf, you will need this.
// (You could use <cstdio>, but I wouldn't bother.)
int main() {
printf("Hello, World!n"); // Mixing iostream and stdio output is a bit of
// a code smell.
int x = 10;
int *location_of_x = &x; // No leading _. Much easier to avoid
// reserved names that way.
// Use %p to print pointers. Note that the value printed here is likely to
// vary from run to run - this makes buffer overflow harder (but not
// impossible) to exploit
printf("%pn",location_of_x);
printf("%dn",x);
// And this is how you indirect through location_of_x
printf("%dn",*location_of_x); //
return 0;
}
相关文章:
- 任何人都可以弄清楚这段代码如何显示运行错误?它打印无限时间 -1 以及正确答案
- 如何在运行时在对象数组中动态追加新对象C++并打印它们
- 为什么如果我从键盘输入EOF克里昂不要在运行窗口打印程序的输出?
- 在代码仍在 C++ QT 中运行时显示打印输出
- 为什么每次运行此程序时&x都会打印不同的值?
- GDB 在程序运行时打印文件名行号
- 我的 c++ 程序不打印任何字符,但是如果我将它们更改为 int,代码可以完美运行
- 尝试打印链表时出现运行时错误
- C++11 打印运行时变量名称等于某个 constexpr 变量
- 当我运行此C 程序时,销售名称1不会打印出来
- 程序运行,但程序中的第二个功能不打印?输出中没有错误
- 为什么当我运行此循环以打印字符串中的每个单词时,我缺少一个值
- 如何使用Qt Windows中的设置路径属性从命令行运行应用程序(.exe)时在命令行上打印日志
- Clang 运行时检查:打印回溯
- 尝试优化和理解打印数字除数的递归函数的运行时
- (可选)在运行时打印到标准输出
- 我希望程序打印数字 0 到 99,但是当我运行代码时,我看到 100 行 99
- 我正在尝试将 s1 中的所有字符更改为"x"。但是,当我运行代码时,编译器刚刚打印出"hello world"11次
- 我的程序将运行,但它会打印出所有 100 个值,这些值应该完全不同
- 如何通过Qt中的root特权以编程方式运行打印命令lpr-p