基于visual c++之windows核心编程代码分析(6)分配和释放可读可写的虚拟内存页面

我们在进行Windows核心编程,经常要用到读取虚拟内存。

我们来亲自实践一个分配与释放可读可写的虚拟内存页面,请见代码实现与注释讲解。

#include <windows.h>
#include <stdio.h>

/*************************************
* int main(void)
* 功能	演示虚拟内存的使用
*
* 参数	未使用
**************************************/
int main(void)
{	
	SIZE_T sizeVirtual = 4000;		//大小
	LPVOID lpRound = (LPVOID)0x100000FF;	//地址
	MEMORY_BASIC_INFORMATION  mbi;	//内存信息

	//分配内存,直接分配已提交的内存
	LPVOID lpAddress = VirtualAlloc(
		lpRound,sizeVirtual,
		MEM_COMMIT|MEM_RESERVE,PAGE_READWRITE
		);
	if(lpAddress == NULL)
	{
		printf("VirtualAlloc error: %d\n",GetLastError());
		return 1;
	}
	printf("Alloc:MEM_COMMIT|MEM_RESERVE\n");
	//复制数据到内存中
	CopyMemory(lpAddress,"hello",lstrlen("hello"));
	printf("分配、复制成功,地址:0x%.8x,内容:%s\n",
		lpAddress,lpAddress);
	//获取内存信息并打印
	VirtualQuery(lpAddress,&mbi,sizeof(mbi));
	printf("使用VirtualQuery获得的信息:\n"
		"BaseAddress:0x%.8x\tAllocationBase:0x%.8x\t"
		"AllocationProtect:0x%.8x\tRegionSize:%u\t"
		"State:0x%.8x\tProtect:0x%.8x\tType:0x%.8x\n",
		mbi.BaseAddress,mbi.AllocationBase,
		mbi.AllocationProtect,mbi.RegionSize,
		mbi.State,mbi.Protect,mbi.Type
		);

	设置为READ-ONLY属性
	//if(!VirtualProtect(lpAddress,0,PAGE_READONLY,NULL))
	//{
	//	printf("VirtualProtect error: %d",GetLastError());
	//	return 1;
	//}
	测试READ-ONLY属性,异常
	//CopyMemory(lpAddress,"read only",lstrlen("read only"));
	//printf(lpAddress);
	获取内存信息并打印
	//VirtualQuery(lpAddress,&mbi,sizeof(mbi));
	//printf("使用VirtualQuery获得的信息:\n"
	//	"BaseAddress:0x%.8x\tAllocationBase:0x%.8x\t"
	//	"AllocationProtect:0x%.8x\tRegionSize:%d\t"
	//	"State:0x%.8x\tProtect:0x%.8x\tType:0x%.8x\n",
	//	mbi.BaseAddress,mbi.AllocationBase,
	//	mbi.AllocationProtect,mbi.RegionSize,
	//	mbi.State,mbi.Protect,mbi.Type
	//	);

	//DECOMMIT释放,页面将变为保留状态
	printf("Free: DECOMMIT\n");
	if(!VirtualFree(lpRound,sizeVirtual,MEM_DECOMMIT))
	{
		printf("VirtualFree error: %d",GetLastError());
		return 1;
	}
	//获取内存信息并打印
	VirtualQuery(lpAddress,&mbi,sizeof(mbi));
	printf("使用VirtualQuery获得的信息:\n"
		"BaseAddress:0x%.8x\tAllocationBase:0x%.8x\t"
		"AllocationProtect:0x%.8x\tRegionSize:%u\t"
		"State:0x%.8x\tProtect:0x%.8x\tType:0x%.8x\n",
		mbi.BaseAddress,mbi.AllocationBase,
		mbi.AllocationProtect,mbi.RegionSize,
		mbi.State,mbi.Protect,mbi.Type
		);
	//释放内存
	printf("Free:RELEASE\n");
	if(!VirtualFree(lpAddress,0,MEM_RELEASE))
	{
		printf("VirtualFree error: %d",GetLastError());
		return 1;
	}
	return 0;
}


 

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

尹成

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值