James346 James346 - 2 months ago 9
C++ Question

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

I am unable to write to a virtual memory block despite it being flagged as PAGE_READWRITE. This is the exception thrown at runtime:

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


Here is the code:

#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);
}

Answer

The flAllocationType parameter of VirtualAlloc must have one of MEM_COMMIT, MEM_RESERVE, MEM_RESET or MEM_RESET_UNDO. The MEM_PHYSICAL is optional flag for flAllocationType.

You have only MEM_PHYSICAL, hence VirtualAlloc fails.

Comments