Virtual Memory Function Demo

来源:互联网 发布:回文c语言 编辑:程序博客网 时间:2024/06/05 18:56
#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;}
0 0