请教两次使用VirtualQuery获取内存保护属性失败
分配完内存之后获取保护属性是正确的,可是在修改完毕保护属性后,再次获取保护属性还是当初分配时的保护属性。自己认为可能是没有成功修改保护属性,
可能是在边界处理上没有做好,但是不知道该怎么去修改。
恳请;)
下面粘贴代码
CString strBuf;
CString strMemoryProtect;
CString strProtect;
PVOID pvAddress;
MEMORY_BASIC_INFORMATION mbi;
MEMORY_BASIC_INFORMATION mbi_after;
//DWORD dwLength;
DWORD dwVirtualQuery;
DWORD dwVirtualQuery_after;
DWORD dwOldProtect;
//分配10MB,PAGE_READWRITE
pvAddress = VirtualAlloc(NULL, 100, MEM_RESERVE | MEM_COMMIT, PAGE_READONLY);
if (pvAddress == NULL)
{
MessageBox("VirtualAlloc Error", "error", MB_OK);
}
else
{
strBuf.Format("Address: 0x%08x", pvAddress);
MessageBox(strBuf, "successful", MB_OK);
}
//获取保护状态/**/
dwVirtualQuery = VirtualQuery(pvAddress, &mbi, sizeof(mbi));
switch (mbi.AllocationProtect)
{
case PAGE_READWRITE:
strMemoryProtect.Format("--PAGE_READWRITE--");
break;
case PAGE_READONLY:
strMemoryProtect.Format("--PAGE_READONLY--");
break;
default:
strMemoryProtect.Format("--Page_****--0x%08x--%d", mbi.AllocationProtect, dwVirtualQuery);
break;
}
MessageBox(strMemoryProtect, "Protect", MB_OK);
strMemoryProtect.Empty();
//修改保护状态
if (VirtualProtect(pvAddress, 100, PAGE_NOACCESS, &dwOldProtect) != 0)
{
switch (dwOldProtect)
{
case PAGE_READWRITE:
strMemoryProtect.Format("--PAGE_READWRITE--");
break;
case PAGE_READONLY:
strMemoryProtect.Format("--PAGE_READONLY--");
break;
default:
strMemoryProtect.Format("--Page_****--0x%08x--%d", dwOldProtect, dwVirtualQuery);
break;
}
strProtect.Format("Change Protect Successful");//\nBefore: %s\nAfter: PAGE_READONLY, strMemoryProtect
MessageBox(strProtect, "successful", MB_OK);
strMemoryProtect.Empty();
}
else
{
MessageBox("Change Protect error", "error", MB_OK);
}
//Sleep(2000);
//重新获取保护状态
dwVirtualQuery_after = VirtualQuery(pvAddress, &mbi_after, sizeof(mbi_after));
switch (mbi_after.AllocationProtect)
{
case PAGE_READWRITE:
strMemoryProtect.Format("2--PAGE_READWRITE--0x%08x", mbi_after.AllocationProtect);
break;
case PAGE_READONLY:
strMemoryProtect.Format("2--PAGE_READONLY--");
break;
default:
strMemoryProtect.Format("2--Page_****--0x%08x--%d", mbi_after.AllocationProtect, dwVirtualQuery_after);
break;
}
MessageBox(strMemoryProtect, "Protect", MB_OK);
strMemoryProtect.Empty();
//释放10MB
if(VirtualFree(pvAddress, 0, MEM_RELEASE))
{
MessageBox("Free Memory Successful", "successful", MB_OK);
}
else
{
MessageBox("Free Memory Error", "error", MB_OK);
}