如何确保VirtualAlloc分配的虚拟内存地址在2-4GB之间 [英] How can I ensure that the virtual memory address allocated by VirtualAlloc is between 2-4GB

查看:91
本文介绍了如何确保VirtualAlloc分配的虚拟内存地址在2-4GB之间的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我尝试使用 while ,但是效果不是很好.有什么办法吗?

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;

推荐答案

使用 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);

这篇关于如何确保VirtualAlloc分配的虚拟内存地址在2-4GB之间的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆