内容摘自:
使用windows内存-VirtualAlloc
#define _CRT_SECURE_NO_WARNINGS
#include<iostream>
#include<windows.h>
#include<conio.h>
using namespace std;
void MemoryStatus()
{
MEMORYSTATUS memStatus;
GlobalMemoryStatus(&memStatus);
cout << "内存繁忙程度=" << memStatus.dwMemoryLoad << endl;
cout << "总物理内存=" << memStatus.dwTotalPhys << endl;
cout << "可用物理内存=" << memStatus.dwAvailPhys << endl;
cout << "总页文件=" << memStatus.dwTotalPageFile << endl;
cout << "可用页文件=" << memStatus.dwAvailPageFile << endl;
cout << "总进程空间=" << memStatus.dwTotalVirtual << endl;
cout << "可用进程空间=" << memStatus.dwAvailVirtual << endl;
}
int main(int argc, char*argv[])
{
cout << "初始状态:" << endl;
MemoryStatus();
//申请内存 保留1G的空间
char* lpv = (char*)VirtualAlloc(NULL, 1024 * 1024 * 1024, MEM_RESERVE, PAGE_READWRITE);
if (lpv == NULL)
{
cout << "没有那么多虚拟空间!" << endl;
return -1;
}
cout << "\n\n申请内存后:" << endl;
MemoryStatus(); // 可用进程空间减少1GB
//提交内存
lpv = (char*)VirtualAlloc(lpv, 1024 * 1024 * 1024, MEM_COMMIT, PAGE_READWRITE);
if (lpv == NULL)
{
cout << "没有那么多物理空间!" << endl;
return -1;
}
cout << "\n\n提交内存后:" << endl;
MemoryStatus();
//使用内存
strcpy(lpv, "abc");
cout << "\n\n使用内存后:" << endl;
MemoryStatus();
//释放内存
VirtualFree(lpv, 1024 * 1024 * 1024, MEM_RELEASE);
system("pause");
return 0;
}
vs2013 win32环境运行