尽管被标记为读写,C++ 仍无法写入虚拟内存

C++ Unable to write to virtual memory despite being marked as read & write

我无法写入虚拟内存块,尽管它被标记为 PAGE_READWRITE。这是运行时抛出的异常:

Exception thrown at 0x722E4AE9 (vcruntime140d.dll) in ConsoleApplication.exe: 0xC0000005: Access violation writing location 0x00000000.

代码如下:

#include <iostream>
#include <windows.h>

int main() {
    char* memblock;

    memblock = new char[8] { 0, 1, 2, 3, 4, 5, 6, 7 };

    LPVOID virtual_memory_area = VirtualAlloc(NULL, 8, MEM_PHYSICAL, PAGE_READWRITE);
    memcpy(virtual_memory_area, memblock, 8);
}

如果您查看错误,则表明您正在尝试写入空指针,因此出现异常。原因是VirtualAlloc失败,返回null。

VirtualAllocflAllocationType 参数必须具有 MEM_COMMITMEM_RESERVEMEM_RESETMEM_RESET_UNDO 之一。 MEM_PHYSICALflAllocationType 的可选标志。

您只有 MEM_PHYSICAL,因此 VirtualAlloc 失败。