#include <Windows.h>
#include <iostream>
using namespace std;
int main()
{
// Reserve virtual address space
LPVOID lpvBase = VirtualAlloc(NULL, 64*1024, MEM_RESERVE, PAGE_READWRITE);
if (lpvBase == NULL)
{
cout << "VirtualAlloc failed with error: " << GetLastError() << endl;
return -1;
}
// Allocate physical storage for the reserved memory pages
LPVOID lpBuffer = VirtualAlloc(lpvBase, 4*1024, MEM_COMMIT, PAGE_READWRITE);
if (lpBuffer == NULL)
{
cout << "VirtualAlloc failed with error: " << GetLastError() << endl;
return -1;
}
// Operate on the allocated memory
sprintf((char*)lpBuffer, "Hello Kitty: %s", "WangYao");
cout << (char*)lpBuffer << endl;
// Decommit allocated memory
BOOL flag = VirtualFree(lpBuffer, 4*1024, MEM_DECOMMIT);
if (flag)
{
cout << "VirtualFree with MEM_DECOMMIT successfully." << endl;
}
else
{
cout << "VirtualFree with MEM_DECOMMIT failed with error: " << GetLastError() << endl;
return -3;
}
// Release allocated memory
flag = VirtualFree(lpvBase, 0, MEM_RELEASE);
if (flag)
{
cout << "VirtualFree with MEM_RELEASE successfully." << endl;
}
else
{
cout << "VirtualFree with MEM_RELEASE failed with error: " << GetLastError() << endl;
return -4;
}
system("pause");
return 0;
}
Virtual Memory Function Demo
最新推荐文章于 2024-08-18 21:26:44 发布