如何在可视C++中读取内存地址

How to read a memory address in Visual C++?

本文关键字:读取 内存 地址 C++ 可视      更新时间:2023-10-16

在ANSI C中,我可以这样做:

const long *address = 0x00000002;  /* Example address */
printf("0x00000002 -> %ld", *address);

控制台将显示该内存地址的内容。但是 VC++ 中的代码抛出:

错误 C2440:"正在初始化":无法从"int"转换为"常量长 *"

是否有从 VC++ 读取内存地址的本机方法,或者我必须调用 API?

提前谢谢。

您的地址表示为整数。您需要将其强制转换为适当类型的指针:

const long *address = reinterpret_cast<const long *>(0x00000002);

你需要用标准C++执行这种转换。我不知道你为什么认为在标准C++中可以省略演员表。

当然,当你运行你的代码时,你会遇到分段错误。

要设置该地址,请使用类似

const long* address = (const long*) 0x0000002;  // C style

const long* address = 
   reinterpret_cast<const long*>(0x000002); // C++ style

顺便说一句,在大多数系统上,0x0000002不是有效的地址(在应用程序的通常虚拟地址空间中)。请参阅关于虚拟内存和虚拟地址空间的维基页面。