最近我放学了几天,想用 C++ 做一个处理内存地址的小程序实验。
我想看到的是,如果一个当前正在运行的程序(我们称之为程序 A)在堆中创建了一个指向 int 对象的指针,是否可以被另一个程序看到并被修改(程序 B)。
所以对于程序 A,这是我的基本代码:
// Program A
#include <iostream>
using namespace std;
int main()
{
// Pointer to an int object in the heap
int *pint = new int(15);
// Display the address of the memory in heap
cout << pint << endl;
// Display the value stored in that address
cout << *pint << endl;
return 0;
}
程序 A 的输出:
0x641030
15
对于程序 B,我查看了如何通过此链接分配特定的内存地址:http: //www.devx.com/tips/Tip/14104
程序 B 的代码是:
// Program B
#include <iostream>
using namespace std;
int main()
{
// assign address 0x641030 to p
int *p = reinterpret_cast< int* > (0x641030);
cout << p << endl;
cout << *p << endl;
return 0;
}
程序 B 的输出:
0x641030
... "Crash"
我不太明白。我期待 15 的显示*p
,但它做了我没想到的事情。
我也尝试分配*p
一个类似的数字,*p = 2000
但是当我尝试这样做时它也崩溃了。
此外,当我显示指针和程序 A ( cout << &pint;
) 和程序 B ( cout << &p;
) 的地址时,它们都显示了相同的内存地址。
有谁知道到底发生了什么?我很感兴趣,但对正在发生的事情感到困惑。另外,我可以做我在 C++/C 中尝试的事情吗?
** 编辑 ** 抱歉没有提及我的平台,但我目前使用的是 Window 7 Professional