确定虚拟内存的可用性是否可读

时间:2013-09-22 15:48:15

标签: c windows performance virtual-memory

假设我想检查win32用户模式应用的整个4GB地址空间。 因为尝试直接从随机位置读取会引发access violation,所以我想首先检查每个页面的可读性:

char* p = 0x00000000;
while (p < 0xf0000000 ) 
{
    MEMORY_BASIC_INFORMATION mbi;
    VirtualQuery ( p , & mbi , 100) ;
    if (!(  mbi.Protect | PAGE_NOACCESS ) )        
         char tmp = *p;
    p = p + PAGE_SIZE;


}

有没有其他方法,更有效率呢?

1 个答案:

答案 0 :(得分:0)

您必须检查状态== MEM_COMMIT和保护!= PAGE_NOACCESS,以避免无效的内存区域。此代码将列出每个有效内存区域的开始和结束地址:


HANDLE hProc = OpenProcess(PROCESS_ALL_ACCESS, FALSE, GetCurrentProcessId());

MEMORY_BASIC_INFORMATION mbi;

while (VirtualQuery(addr, &mbi, sizeof(mbi)))
{
    if (mbi.State == MEM_COMMIT && mbi.Protect != PAGE_NOACCESS)
    {
        std::cout << "base : 0x" << std::hex << mbi.BaseAddress << " end : 0x" << std::hex << (uintptr_t)mbi.BaseAddress + mbi.RegionSize << "\n";
    }
    addr += mbi.RegionSize;
}