gpt4 book ai didi

C++ Mac OS X 10.11.2 vm_read 给出错误的值

转载 作者:行者123 更新时间:2023-11-30 05:33:33 25 4
gpt4 key购买 nike

我正在尝试在我的 Mac 操作系统上编写一个简单的内存读取器/写入器,但我遇到了问题。

写入方面工作正常,甚至 vm_read 返回 KERN_SUCCESS。但是当我尝试打印我在 vm_read 中引用的缓冲区时,它给了我一个错误的值。

#include <iostream>
#include <mach/mach_init.h>
#include <mach/mach.h>

using namespace std;

int main() {
int start = 1337;
int value = 100;

uintptr_t buf;
uint32_t bytesRead;

task_t task;

task_for_pid(current_task(), getpid(), &task);

cout << "Step 1 (before write, should = 1337): " << start << endl;

int reason = 0;
if ((reason = vm_write(task, (uintptr_t) &start, (uintptr_t) &value, sizeof(int))) != KERN_SUCCESS) {
cout << "Failed to write: " << reason << endl;
}

if ((reason = vm_read(task, (uintptr_t) &start, sizeof(int), &buf, &bytesRead)) != KERN_SUCCESS) {
cout << "Failed to read: " << reason << endl;
}

cout << "Step 2 (after write, should = 100): " << buf << endl;
return 0;
}

以下代码输出:

/Users/Jonathan/Library/Caches/CLion12/cmake/generated/4f3c65b6/4f3c65b6/Debug/helloworld
Step 1 (before write, should = 1337): 1337
Step 2 (after write, should = 100): 4415766528

Process finished with exit code 0

第 2 步应该打印 100,因为我将 100 的值写入 start 变量。(如果我执行 cout << start << endl;,它会打印 100)。

知道哪里出了问题吗?谢谢!

最佳答案

尝试将第 2 步替换为:

cout << "Step 2 (after write, should = 100): " << (*(int*)buf) << endl;

Buf 是指向您读取的数据的指针,因此您必须取消引用它才能从那里获取实际的整数。

关于C++ Mac OS X 10.11.2 vm_read 给出错误的值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34734179/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com