*《精通Windows API》 5.4.2 分配和釋放可讀可寫的虛擬記憶體頁面

來源:互聯網
上載者:User
/* *************************************《精通Windows API》 * 範例程式碼* virtual.c* 5.4.2  分配和釋放可讀可寫的虛擬記憶體頁面**************************************//* 標頭檔 */#include <windows.h>#include <stdio.h>/************************************** int main(void)* 功能示範虛擬記憶體的使用** 參數未使用**************************************/int main(void){SIZE_T sizeVirtual = 4000;//大小LPVOID lpRound = (LPVOID)0x100000FF;//地址MEMORY_BASIC_INFORMATION  mbi;//記憶體資訊//分配記憶體,直接分配已提交的記憶體LPVOID lpAddress = VirtualAlloc(lpRound,sizeVirtual,MEM_COMMIT|MEM_RESERVE,PAGE_READWRITE);if(lpAddress == NULL){printf("VirtualAlloc error: %d\n",GetLastError());return 1;}printf("Alloc:MEM_COMMIT|MEM_RESERVE\n");//複製資料到記憶體中CopyMemory(lpAddress,"hello",lstrlen("hello"));printf("分配、複製成功,地址:0x%.8x,內容:%s\n",lpAddress,lpAddress);//擷取記憶體資訊並列印VirtualQuery(lpAddress,&mbi,sizeof(mbi));printf("使用VirtualQuery獲得的資訊:\n""BaseAddress:0x%.8x\tAllocationBase:0x%.8x\t""AllocationProtect:0x%.8x\tRegionSize:%u\t""State:0x%.8x\tProtect:0x%.8x\tType:0x%.8x\n",mbi.BaseAddress,mbi.AllocationBase,mbi.AllocationProtect,mbi.RegionSize,mbi.State,mbi.Protect,mbi.Type);////設定為READ-ONLY屬性//if(!VirtualProtect(lpAddress,0,PAGE_READONLY,NULL))//{//printf("VirtualProtect error: %d",GetLastError());//return 1;//}////測試READ-ONLY屬性,異常//CopyMemory(lpAddress,"read only",lstrlen("read only"));//printf(lpAddress);////擷取記憶體資訊並列印//VirtualQuery(lpAddress,&mbi,sizeof(mbi));//printf("使用VirtualQuery獲得的資訊:\n"//"BaseAddress:0x%.8x\tAllocationBase:0x%.8x\t"//"AllocationProtect:0x%.8x\tRegionSize:%d\t"//"State:0x%.8x\tProtect:0x%.8x\tType:0x%.8x\n",//mbi.BaseAddress,mbi.AllocationBase,//mbi.AllocationProtect,mbi.RegionSize,//mbi.State,mbi.Protect,mbi.Type//);//DECOMMIT釋放,頁面將變為保留狀態printf("Free: DECOMMIT\n");if(!VirtualFree(lpRound,sizeVirtual,MEM_DECOMMIT)){printf("VirtualFree error: %d",GetLastError());return 1;}//擷取記憶體資訊並列印VirtualQuery(lpAddress,&mbi,sizeof(mbi));printf("使用VirtualQuery獲得的資訊:\n""BaseAddress:0x%.8x\tAllocationBase:0x%.8x\t""AllocationProtect:0x%.8x\tRegionSize:%u\t""State:0x%.8x\tProtect:0x%.8x\tType:0x%.8x\n",mbi.BaseAddress,mbi.AllocationBase,mbi.AllocationProtect,mbi.RegionSize,mbi.State,mbi.Protect,mbi.Type);//釋放記憶體printf("Free:RELEASE\n");if(!VirtualFree(lpAddress,0,MEM_RELEASE)){printf("VirtualFree error: %d",GetLastError());return 1;}return 0;}

相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.