How can I ensure that the virtual memory address allocated by VirtualAlloc is between 2-4GB

与世无争的帅哥 提交于 2021-02-17 07:13:27

问题


I tried to use while, but the effect is not very good. Is there any way to do it?

bool found = false;
uintptr_t memaddr = 0;
int n = 0;
while (!found && n < 10)
{
    n += 1;
    memaddr = (uintptr_t)VirtualAlloc(0, 4, MEM_COMMIT, PAGE_EXECUTE_READWRITE);
    int g = memaddr / 1024 / 1024 / 1024;
    cout << "memaddr: " << memaddr << endl;
    if (g >= 2 && g <= 4)
    {
        found = true;
    }
}
cout << hex << memaddr << endl;

回答1:


Use the lpAddress parameter of VirtualAlloc

#include "pch.h"
#include <iostream>
#include <Windows.h>
#include <TlHelp32.h>
#include <Psapi.h>

using namespace std;

MODULEINFO GetModuleInfo(const wchar_t* name)
{
    MODULEINFO mi{ 0 };
    HMODULE hMod = GetModuleHandle(name);
    GetModuleInformation(GetCurrentProcess(), hMod, &mi, sizeof(mi));
    return mi;
}

MODULEINFO mi = GetModuleInfo(L"x64.exe");

BYTE* newmem = (BYTE*)VirtualAlloc((BYTE*)((uintptr_t)mi.lpBaseOfDll - 0x10000), 500, 
    MEM_COMMIT | MEM_RESERVE, PAGE_EXECUTE_READWRITE);

cout << (uintptr_t)newmem / 1024 / 1024 / 1024 << endl;

BYTE* newmem2 = (BYTE*)VirtualAlloc((BYTE*)((uintptr_t)newmem - 0x10000), 4,
    MEM_COMMIT | MEM_RESERVE, PAGE_EXECUTE_READWRITE);

if (newmem  != 0)  VirtualFree(newmem,  0,  MEM_RELEASE);
if (newmem2 != 0)  VirtualFree(newmem2, 0,  MEM_RELEASE);


来源:https://stackoverflow.com/questions/63275557/how-can-i-ensure-that-the-virtual-memory-address-allocated-by-virtualalloc-is-be

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!