c++ - `VirtualAllocEx`指定不同的起始地址时返回相同的地址?

标签 c++ winapi virtualalloc

我试图让 calc.exe 显示一个消息框,但 calc.exe 总是在我执行我的程序时崩溃。因此,我尝试将代码注入(inject)到我自己的进程中,以便查看调试消息。这样做给了我指向 pData->msg 的异常“访问冲突...无法执行...”。然后我发现 pThreadpData 得到了相同的地址。这怎么可能?我实际上将 VirtualAllocExlpAddress 设置为 pPagepPage + 128 以获得相同的起始地址。

// Allocate page
void *pPage = VirtualAllocEx(hProcess, NULL, 256, MEM_RESERVE, PAGE_EXECUTE_READWRITE);

// Commit memory for thread procedure
void *pThread = VirtualAllocEx(hProcess, pPage, 128, MEM_COMMIT, PAGE_EXECUTE_READWRITE);

// Commit memory for thread data
void *pData = VirtualAllocEx(hProcess, (void*)((long long)pPage + 128), 128, MEM_COMMIT, PAGE_EXECUTE_READWRITE);

// WriteProcessMemory, do stuff

// Release memory
VirtualFreeEx(hProcess, pPage, 256, MEM_RELEASE);

最佳答案

VirtualAllocEx 分配内存,内存页大小为 4096 字节。

dwSize [in] The size of the region, in bytes. If the lpAddress parameter is NULL, this value is rounded up to the next page boundary. Otherwise, the allocated pages include all pages containing one or more bytes in the range from lpAddress to lpAddress+dwSize. This means that a 2-byte range straddling a page boundary causes both pages to be included in the allocated region.

lpAddress [in, optional] The pointer that specifies a desired starting address for the region of pages that you want to allocate. If you are reserving memory, the function rounds this address down to the nearest multiple of the allocation granularity.

尝试使用堆函数(HeapAlloc、HeapFree、HeapCreate)。

或者你可以这样做:

// Allocate page
void *pPage = VirtualAllocEx(hProcess, NULL, 256, MEM_RESERVE | MEM_COMMIT, PAGE_EXECUTE_READWRITE);

// Commit memory for thread data
void *pData = (char*)pPage + 128;

// WriteProcessMemory, do stuff

// Release memory
VirtualFreeEx(hProcess, pPage, 256, MEM_RELEASE);

关于c++ - `VirtualAllocEx`指定不同的起始地址时返回相同的地址?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33854462/

相关文章:

c# - C#中的VirtualAlloc分配大内存

c++ - 简单的 GUI IDE?

c++ - itoa 和 sprintf 哪个效率高?

c++ - 创建 Windows 安装程序

c++ - 运行单元测试时的内存泄漏检测

winapi - 在大型阵列上使用VirtualAlloc保留与提交+保留内存的优势

c++ - 如何筛选 IShellFolder::EnumObjects 结果

python - 使用 pythoncom.CoUninitialize() 和 wmi 时发生 Win32 异常

c - SetWindowText 显示来自 InternetReadFile() 的无法识别的代码

c++ - virtualalloc 的问题