WinApi学习笔记-第一次离内存这么近

2022-05-09 11:11:05 浏览数 (1)

代码语言:javascript复制
#include <windows.h>
#include <stdio.h>
#include <iostream>
using namespace std;
//参数1堆句柄,参数2内存地址指针
DWORD PrintHeapSize(HANDLE hHeap,LPVOID lpMem)
{
    SIZE_T dwHeapSize;
    dwHeapSize = HeapSize(hHeap,HEAP_NO_SERIALIZE,lpMem);
    if(dwHeapSize == -1)
    {
        std::cout<<"GetHeapSizeError"<<std::endl;
        return 1;
    }
    std::cout<<"内存块大小为:"<<dwHeapSize<<std::endl;
}
int main()
{
    SYSTEM_INFO si;//系统信息
    HANDLE hHeap;//堆句柄
    HANDLE hHeap2;
    HANDLE hHeap3;
    LPVOID lpMem;//内存块指针
    LPVOID lpReAlloc;//内存块大小调整后的指针
    DWORD dwHeapSize;//堆大小
    HANDLE hHeaps[24];//用于存储进程中所有堆句柄
    DWORD dwHeapNum;
    GetSystemInfo(&si);
    cout<<"系统内存分页大小:"<<si.dwPageSize<<"Byte"<<endl<<"系统内存分配粒度"<<si.dwAllocationGranularity<<endl;
    hHeap = HeapCreate(HEAP_NO_SERIALIZE,si.dwPageSize,si.dwPageSize*10);
    cout<<"创建了一个堆,初始化大小为1页,最大为10页"<<endl;
    hHeap2 = HeapCreate(HEAP_NO_SERIALIZE,0,0);
    cout<<"创建堆,初始化大小为1页,大小可变"<<endl;
    hHeap3 = GetProcessHeap();
    cout<<"获取系统已经存在的堆"<<endl;
    if(hHeap == NULL||hHeap2 == NULL||hHeap3 == NULL)
    {
        cout<<"创建内存失败"<<GetLastError()<<endl;
        return 1;
    }
    dwHeapNum = GetProcessHeaps(24,hHeaps);
    if(dwHeapNum == 0)
    {
        printf("Get All Heaps Error");
        return 1;
    }
    else
    {
        cout<<"当前一共有"<<dwHeapNum<<"个堆"<<endl;
    }
    lpMem = HeapAlloc(hHeap2,HEAP_ZERO_MEMORY,si.dwPageSize*3);
    if(lpMem==NULL)
    {
        cout<<"分配内存失败"<<GetLastError()<<endl;
        return 1;
    }
    printf("在堆上分配内存成功,起始地址为0x%xn",lpMem);
    //调用辅助函数,打印内存块大小
    PrintHeapSize(hHeap2,lpMem);
    lpReAlloc = HeapReAlloc(hHeap2,HEAP_ZERO_MEMORY,lpMem,si.dwPageSize*11);
    printf("重新分配内存,调整内存大小为11个分页,新地址为0x%xn",lpReAlloc);
    PrintHeapSize(hHeap2,lpReAlloc);
    CHAR A;
    cin>>A;

}

0 人点赞