/**
* 进程默认堆操作,进程多个其他堆创建
*/
#include <Windows.h>
#include <stdio.h>
int main()
{
SYSTEM_INFO si;
GetSystemInfo(&si);
HANDLE hHeap1;
hHeap1 = HeapCreate(
HEAP_NO_SERIALIZE,
si.dwPageSize*2, //堆初始大小为 2页
si.dwPageSize*10 //堆最大初始化为10页大小
);
if (hHeap1 == NULL)
{
printf("创建堆失败: %d\n", GetLastError());
return 1;
}
printf("创建堆成功,初始大小为2页,最大为10页\n");
HANDLE hHeap2;
hHeap2 = HeapCreate(HEAP_NO_SERIALIZE,
0,
0);
if (hHeap2 == NULL)
{
printf("创建堆失败:%d\n", GetLastError());
return 1;
}
printf("创建堆成功,初始大小为1页,可以增长\n");
// 查看堆数量
DWORD dwHeapNum;
dwHeapNum = GetProcessHeaps(0,NULL);
if (dwHeapNum == 0)
{
printf("GetProcessHeaps error: %d\n", GetLastError());
return 3;
}
printf("当前进程中堆的数量为:%d\n", dwHeapNum);
// 在堆上分配内存
PVOID lpMem1, lpMem2;
lpMem1 = HeapAlloc(hHeap1,HEAP_ZERO_MEMORY,si.dwPageSize*3);
if (lpMem1 == NULL)
{
printf("HeapAlloc error: %d\n", GetLastError());
return 4;
}
printf("在堆 hHeap1 上分配内存成功,起始地址为:0x%x\n", lpMem1);
// 调整lpMem1指向堆内存大小
PVOID lpReAllocl;
lpReAllocl = HeapReAlloc(
hHeap1,
HEAP_ZERO_MEMORY,
lpMem1,
si.dwPageSize*11 //会分配失败,堆 hHeap1总共大小只有10页
);
if (lpReAllocl == NULL)
{
printf("HeapRealloc error: %d\n",GetLastError());
//return 5;
}
// 在堆 hHeap2 上分配内存
lpMem2 = HeapAlloc(hHeap2,HEAP_ZERO_MEMORY,si.dwPageSize*11);
if (lpMem2 == NULL)
{
printf("HeapAlloc error: %d\n", GetLastError());
return 4;
}
printf("在堆 hHeap2 上分配内存成功,起始地址为:0x%x\n", lpMem2);
// 调整lpMem1指向堆内存大小
PVOID lpReAlloc2;
lpReAlloc2 = HeapReAlloc(
hHeap2,
HEAP_ZERO_MEMORY,
lpMem2,
si.dwPageSize*11 //会分配失败,堆 hHeap1总共大小只有10页
);
if (lpReAlloc2 == NULL)
{
printf("HeapRealloc error: %d\n",GetLastError());
//return 5;
}
// 释放堆内存
if (!HeapFree(hHeap1,HEAP_NO_SERIALIZE, lpMem1))
{
printf("lpMem1 HeapFree error: %d\n", GetLastError());
return 7;
}
else printf("lpMem1 HeapFree success.\n");
if (!HeapFree(hHeap2,HEAP_NO_SERIALIZE, lpMem2))
{
printf("lpMem2 HeapFree error: %d\n", GetLastError());
return 8;
}
else printf("lpMem2 HeapFree success.\n");
// 堆一销毁
if (!HeapDestroy(hHeap1))
{
printf("heap1 detroy failed.\n");
return 9;
}
printf("销毁成功!\n");
// 堆2销毁
if (!HeapDestroy(hHeap1))
{
printf("heap1 detroy failed.\n");
return 9;
}
printf("销毁成功!\n");
// 进程默认堆
HANDLE hHeap3;
hHeap3 = GetProcessHeap();
PVOID lpMem3;
lpMem3 = HeapAlloc(hHeap3, HEAP_NO_SERIALIZE,
si.dwPageSize*3);
if (lpMem3 == NULL)
{
printf("HeapAlloc error: %d\n", GetLastError());
return 10;
}
printf("进程默认堆上分配内存成功!\n");
// 释放进程默认堆
if (!HeapFree(hHeap3, HEAP_NO_SERIALIZE, lpMem3))
{
printf("HeapFree error: %d\n", GetLastError());
return 11;
}
printf("在进程默认堆上释放内存成功!\n");
// 进程默认堆不能销毁
system("pause");
return 0;
}

2131

被折叠的 条评论
为什么被折叠?



