0

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;
januw a
  • 2,056
  • 5
  • 18
  • 39
  • 1
    You are leaking virtual memory, as you don't call `VirtualFree()` on the memory returned by `VirtualAlloc()` – Remy Lebeau Aug 06 '20 at 01:36
  • 2
    *Why* do you want to ensure that the value returned by `VirtualAlloc()` is between 2-4 GB?? In any event, if `VirtualAlloc()` returns a value outside your desired range, it will be because the OS has determined that is appropriate. There is also the problem in your loop that it calls `VirtualAlloc()` repeatedly, but doesn't release it (using `VirtualFree()` - that is a memory leak which - unless it happens to allocate a block in your desired region, will probably bring the OS to its knees. – Peter Aug 06 '20 at 01:39
  • 2
    Why do you need to check the address range that the returned memory pointer falls within? The whole purpose of the `lpAddress` parameter of `VirtualAlloc()` is so you can tell it where to allocate. Setting that to NULL lets `VirtualAlloc()` allocate wherever it wants. – Remy Lebeau Aug 06 '20 at 01:39
  • 5
    `VirtualAlloc` has a `lpAddress` parameter. Did you try that? – Paul Sanders Aug 06 '20 at 01:41
  • You need to specify lpAddress and also change the MEM_COMMIT parameter to MEM_COMMIT | MEM_RESERVE. – Anonymous1847 Aug 06 '20 at 02:41

1 Answers1

0

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);
januw a
  • 2,056
  • 5
  • 18
  • 39