效果

源碼
#include
#include
int main(int argc, PCHAR argv[]){
SIZE_T sizeVirtual = 4000;//大小
LPVOID lpRound = (LPVOID)0x100000FF;//地址
MEMORY_BASIC_INFORMATION mbi;//內(nèi)存信息
//分配內(nèi)存,直接分配已提交的內(nèi)存
LPVOID lpAddress = VirtualAlloc(lpRound, sizeVirtual, MEM_COMMIT | MEM_RESERVE, PAGE_READWRITE);
if (lpAddress == NULL){
printf("分配虛擬內(nèi)存失敗: %d\n", GetLastError());
return 1;
}
printf("分配成功: MEM_COMMIT | MEM_RESERVE 內(nèi)存已從 空閑 提交為 已提交\n");
//復(fù)制數(shù)據(jù)到內(nèi)存中
CopyMemory(lpAddress, TEXT("misaka"), lstrlen(TEXT("misaka")));
printf("復(fù)制成功,地址: 0x%x, 內(nèi)容: %s\n", lpAddress, lpAddress);
//獲取內(nèi)存信息并打印
VirtualQuery(lpAddress, &mbi, sizeof(mbi));
printf("使用VirtualQuery函數(shù)獲得的信息是;\n");
printf("基址: 0x%.8x 分配基址: 0x%.8x\n", mbi.BaseAddress, mbi.AllocationBase);
printf("分配保護(hù): 0x%.8x 區(qū)域大小: 0x%.8x\n", mbi.AllocationProtect, mbi.RegionSize);
printf("狀態(tài): 0x%.8x 保護(hù): 0x%.8x 類型: 0x%.8x\n", mbi.State, mbi.Protect, mbi.Type);
//釋放內(nèi)存,將頁(yè)面變?yōu)楸A魻顟B(tài)
printf("釋放內(nèi)存,將頁(yè)面變?yōu)楸A魻顟B(tài) DECOMMIT\n");
if (!VirtualFree(lpRound, sizeVirtual, MEM_DECOMMIT)){
printf("釋放虛擬內(nèi)存失敗: %d\n", GetLastError());
return 1;
}
//再次獲取內(nèi)存信息
VirtualQuery(lpAddress, &mbi, sizeof(mbi));
printf("使用VirtualQuery函數(shù)獲得的信息是;\n");
printf("基址: 0x%.8x 分配基址: 0x%.8x\n", mbi.BaseAddress, mbi.AllocationBase);
printf("分配保護(hù): 0x%.8x 區(qū)域大小: 0x%.8x\n", mbi.AllocationProtect, mbi.RegionSize);
printf("狀態(tài): 0x%.8x 保護(hù): 0x%.8x 類型: 0x%.8x\n", mbi.State, mbi.Protect, mbi.Type);
//釋放內(nèi)存,將頁(yè)面變?yōu)榭臻e狀態(tài)
printf("釋放內(nèi)存,將頁(yè)面變?yōu)榭臻e狀態(tài) RELEASE\n");
if (!VirtualFree(lpAddress, 0, MEM_RELEASE)){
printf("釋放虛擬內(nèi)存失敗: %d\n", GetLastError());
return 1;
}
//雖然設(shè)置的地址是0x100000FF,大小4000(FA0),跨越了兩個(gè)虛擬內(nèi)存頁(yè)
//所以VirtualAlloc函數(shù)自動(dòng)進(jìn)行了對(duì)齊,這是虛擬內(nèi)存分配對(duì)齊機(jī)制
//代碼中第二次使用VirtualFree參數(shù)不同,使用MEM_RELEASE參數(shù)釋放虛擬內(nèi)存必須
//這樣釋放對(duì)齊后的頁(yè)基址
getchar();
return 0;
}