【发布时间】:2022-01-24 00:46:13
【问题描述】:
我很好奇,所以我尝试这样做:
第一个程序:
#include <iostream>
using namespace std;
int a = 5;
int main()
{
cout << "Value of a: " << a << endl;
cout << "Address of a: " << &a << endl;
system("pause");
return 0;
}
输出:
- a 的值:5
- a的地址:0x472010
第二个节目:
#include <iostream>
using namespace std;
int* p = reinterpret_cast<int*>(0x472010);
int main()
{
cout << "Value of p: " << *p << endl;
cout << "The address that the pointer points to: " << p << endl;
cout << endl;
system("pause");
return 0;
}
所以,我想读取变量“a”的值 'p' 指针属于另一个程序,'p' 指针指向特定地址。
在我运行第二个程序之前一切都很好,因为第二个程序没有给出想要的结果
输出第二个程序:
- p 值:4661264
- 指针指向的地址:0x472010
如果我保持第一个程序的窗口打开,结果不会改变。
我保证我是初学者,我正在尝试新事物
我做错了什么?
【问题讨论】:
-
FWIW,每次运行程序时,地址都会改变。见en.wikipedia.org/wiki/Address_space_layout_randomization
-
在 90 年代,这种事情在 16 位 Windows 上是可能的。由于任何程序都可能破坏另一个程序(或操作系统本身)的内存,因此系统的稳定性受到损害,并且每天多次重新启动计算机是很常见的。今天,错误的代码很少影响其他应用程序,因为一个进程无法访问其他进程的内存。