c++winapimemory-managementvirtual-memory

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


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;

Solution

  • 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);