【发布时间】:2020-05-22 05:05:18
【问题描述】:
我想从已知内存位置开始的进程内存中读取 64 个字节。为此,我编写了以下C++ 代码:
#include <iostream>
#include <Windows.h>
#include <iomanip>
using namespace std;
int main() {
LPCVOID Address = (LPCVOID)0x0000029FC0C41FF0; // the memory address where I want to read from
byte buffer[64];
HANDLE hProcess = OpenProcess(PROCESS_VM_READ, 0, 13868); // the process ID of the process
ReadProcessMemory(hProcess, Address, &buffer, sizeof(buffer), 0);
const int siz_ar = sizeof(buffer) / sizeof(int); // the rest is trying to display the bytes read on stdout
for (int i = 0; i < siz_ar; ++i)
cout << hex << setfill('0') << setw(2) << buffer[i] << " ";
cout << endl;
}
它不起作用并在控制台输出以下奇怪的字符串:
0╠ 0╠ 0╠ 0╠ 0╠ 0╠ 0╠ 0╠
如何更正此程序以从特定进程(由进程 ID 指定)的特定内存地址读取原始字节?
【问题讨论】:
-
您的代码不会执行任何错误检查(例如,检查
OpenProcess是否成功,ReadProcessMemory是否成功等)。 先这样做。 -
可能是早上太早了,但是for循环中的
hex变量是从哪里来的呢?此外,在生产代码中,using namespace std;不受欢迎,因为命名空间污染。详情见这里:softwareengineering.stackexchange.com/questions/236404/… -
下一步是添加错误检查。阅读您调用的两个 api 函数的文档,其中告诉您如何检查错误。
-
@schaiba 这是
std::hex,所以是的,为时过早! ;-) -
在将
buffer[i]传递给cout时,您需要将其转换为int。operator<<将byte(又名unsigned char)视为与char相同,这就是您无法正确查看十六进制值的原因。也就是说,您的buffer包含字节CC CC CC CC CC CC CC CC,这是未初始化堆栈内存的常见字节模式,这意味着您的ReadProcessMemory()调用失败。
标签: c++ windows winapi memory memory-management