在Win32中管理虚拟内存——举例

以下两个编程例子: 

整块方式使用虚拟内存页 
分块方式使用虚拟内存页 

(一)整块方式,分以下两步
  (1)预留+提交
  (2)释放
#include <stdio.h>
#include <windows.h>
int main(int argc, char*argv[])
{
 LPVOID lpvBase;      // base address of the test memory
 int i;
 for(i=0; ; i++)
 {
  lpvBase = VirtualAlloc(  // (1)
   NULL,     // system selects address
   102400,     // size of allocation
   MEM_RESERVE|MEM_COMMIT, // allocate reserved and committed pages
   PAGE_READWRITE);        // both read and write
  if (NULL == lpvBase )
  {
   printf("call VirtualAlloc fail!\n");
   exit(1);
  }
  else
  {
   printf("call VirtualAlloc LastError=%d\n", GetLastError());
   strcpy((char*)lpvBase, "I am a boy!");
   VirtualFree(lpvBase, 0, MEM_RELEASE);// (2)
   printf("call VirtualFree LastError=%d\n", GetLastError());
  }
  Sleep(0);
 }
}
 其中,VirtualFree(lpvBase, 0, MEM_RELEASE);
 等价于
    VirtualFree(lpvBase, 0, MEM_DECOMMIT);
    VirtualFree(lpvBase, 0, MEM_RELEASE);
 但绝不等价于
    VirtualFree(lpvBase, 0, MEM_DECOMMIT\|MEM_RELEASE);
 也就是说,*MEM_DECOMMIT\|MEM_RELEASE组合方式是不允许的,造成虚拟内存的泄露。

(二)分段方式
 (1)预留
 (2)提交子页
 (3)解除提交
 (4)释放

#include <stdio.h>
#include <windows.h>int main(int argc, char*argv[])
{
 LPVOID lpvBase, lpPage3;      // base address of the test memory
 int i;
 for(i=0; ; i++)
 {
  lpvBase = VirtualAlloc(  // (1)
   NULL,     // system selects address
   4096*8,     // size of allocation
   MEM_RESERVE,   // allocate reserved pages
   PAGE_READWRITE);        // both read and write
  if (NULL == lpvBase )
  {
   printf("call VirtualAlloc MEM_RESERVE fail!\n");
   exit(1);
  }
  else
  {
   printf("call VirtualAlloc MEM_RESERVE, LastError=%d\n", GetLastError());
   lpPage3 = VirtualAlloc(   //(2)
    (char*)lpvBase+(4096*2), // user selects address
    4096,      // size of allocation
    MEM_COMMIT,     // allocate committed pages
    PAGE_READWRITE);   // both read and write
   if (NULL == lpPage3 )
   {
    printf("call VirtualAlloc MEM_COMMIT fail!\n");
    exit(1);
   }
   printf("call VirtualAlloc MEM_COMMIT, LastError=%d\n", GetLastError());
   strcpy((char*)lpPage3, "I am a boy!");
   VirtualFree((char*)lpvBase+(4096*2), 4096, MEM_DECOMMIT); //(3)
   printf("call VirtualFree MEM_DECOMMIT, LastError=%d\n", GetLastError());
   VirtualFree(lpvBase, 0, MEM_RELEASE); //(4)
   printf("call VirtualFree MEM_RELEASE, LastError=%d\n", GetLastError());
  }
  Sleep(0);
 }
}


转载于:https://www.cnblogs.com/java201408/archive/2013/03/15/3900971.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值