有了之前两篇的基础,现在已经了解了 Windows 系统是如何管理内存的,以及各种分配与释放的方法。分配、释放内存最终目的还是要使用内存,所以要研究如何使用内存,如复制、填充等。
示例程序:
#include<windows.h>
#include<stdio.h>
#define MEM_BLOCK_SIZE 32
BOOL ShowMemContent(LPVOID lpMem,SIZE_T dwSize)
{
BYTE lpShow[MEM_BLOCK_SIZE];
INT i=0;
if(dwSize>MEM_BLOCK_SIZE)
{
printf("over-flow");
return FALSE;
}
CopyMemory((LPVOID)lpShow,lpMem,dwSize);
for(i;i<dwSize;i++)
{
printf("%.2x ",lpShow[i]);
if(!((i+1)%16))
{
printf("\n");
}
}
printf("\n");
return TRUE;
}
int main()
{
HANDLE hHeap = GetProcessHeap();
LPVOID lpSrc;
LPVOID lpDis;
lpSrc = HeapAlloc(hHeap,0,MEM_BLOCK_SIZE);
lpDis = HeapAlloc(hHeap,0,MEM_BLOCK_SIZE);
printf("HeapAlloc 分配但不清零: \n");
ShowMemContent(lpDis,MEM_BLOCK_SIZE);
ZeroMemory(lpDis,MEM_BLOCK_SIZE);
printf("ZeroMemory 清零:\n");
ShowMemContent(lpDis,MEM_BLOCK_SIZE);
FillMemory(lpSrc,MEM_BLOCK_SIZE,0xBB);
FillMemory(lpSrc,MEM_BLOCK_SIZE/2,0xAA);
CopyMemory(lpDis,lpSrc,MEM_BLOCK_SIZE);
printf("FillMemory fill src and copy to dis\n");
ShowMemContent(lpDis,MEM_BLOCK_SIZE);
HeapFree(hHeap,0,lpSrc);
HeapFree(hHeap,0,lpDis);
return 0;
}
运行结果:
HeapAlloc 分配但不清零:
2f 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00
00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00
ZeroMemory 清零:
00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00
00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00
FillMemory fill src and copy to dis
aa aa aa aa aa aa aa aa aa aa aa aa aa aa aa aa
bb bb bb bb bb bb bb bb bb bb bb bb bb bb bb bb
本篇博客出自 阿修罗道,转载请注明出处:http://blog.csdn.net/fansongy/article/details/7077842