![ContractedBlock.gif](https://www.cnblogs.com/Images/OutliningIndicators/ContractedBlock.gif)
![ExpandedBlockStart.gif](https://www.cnblogs.com/Images/OutliningIndicators/ExpandedBlockStart.gif)
#include <windows.h>
#include <stdio.h>
#include <iostream>
using namespace std;
int main(void)
{
SIZE_T sizeVirtual = 4000;//大小
LPVOID lpRound = (LPVOID)0x100000FF;//地址
MEMORY_BASIC_INFORMATION mbi;//内存信息
//分配内存
//MEM_COMMIT|MEM_RESERVE直接把内存从空闲状态变为已提交的状态
//PAGE_READWRITE 内存的保护属性
LPVOID lpAddress = VirtualAlloc(lpRound,sizeVirtual,MEM_COMMIT|MEM_RESERVE,PAGE_READWRITE);
if(lpAddress == NULL)
{
std::cout<<"error"<<GetLastError()<<std::endl;
return 1;
}
std::cout<<"alloc:MEM_COMMIT|MEM_RESERVE"<<std::endl;
CopyMemory(lpAddress,"hello Memmory",lstrlen("hello Memmory"));
std::cout<<"分配 复制成功"<<std::endl<<"地址:0x"<<lpAddress<<std::endl;
std::cout<<"内容:"<<(LPSTR)lpAddress<<std::endl;
//获取内存信息
VirtualQuery(lpAddress,&mbi,sizeof(mbi));
cout<<"VirtualQuery获取信息"<<endl;
cout<<"基地址:0x"<<mbi.BaseAddress<<endl;
cout<<"内存的保护属性"<<mbi.AllocationProtect<<endl;
cout<<"内存状态:0x"<<mbi.State<<endl;
VirtualFree(lpRound,sizeVirtual,MEM_DECOMMIT);
cout<<"内存以decommit释放"<<endl<<"再次查看内存信息:"<<endl;
//获取内存信息
VirtualQuery(lpAddress,&mbi,sizeof(mbi));
cout<<"VirtualQuery获取信息"<<endl;
cout<<"基地址:0x"<<mbi.BaseAddress<<endl;
cout<<"内存的保护属性"<<mbi.AllocationProtect<<endl;
cout<<"内存状态:0x"<<mbi.State<<endl;
VirtualFree(lpAddress,0,MEM_RELEASE);
cout<<"内存被释放"<<endl<<"再次查看内存信息:"<<endl;
//获取内存信息
VirtualQuery(lpAddress,&mbi,sizeof(mbi));
cout<<"VirtualQuery获取信息"<<endl;
cout<<"基地址:0x"<<mbi.BaseAddress<<endl;
cout<<"内存的保护属性"<<mbi.AllocationProtect<<endl;
cout<<"内存状态:0x"<<mbi.State<<endl;
CHAR a;
std::cin>>a;
}