以下两个编程例子:
整块方式使用虚拟内存页
分块方式使用虚拟内存页
(一)整块方式,分以下两步
(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);
}
}
在Win32中管理虚拟内存——举例
最新推荐文章于 2024-03-07 09:55:20 发布