프로세스 힙 가져오기

이 예제에서는 GetProcessHeaps 함수를 사용하여 기본 프로세스 힙 및 현재 프로세스에 대해 활성 상태인 모든 프라이빗 힙에 대한 핸들을 검색하는 방법을 보여 줍니다.

이 예제에서는 GetProcessHeaps 를 두 번 호출하고, 먼저 필요한 버퍼의 크기를 계산하고, 버퍼로 핸들을 검색하는 데 다시 호출합니다. 버퍼는 GetProcessHeap에서 반환된 핸들을 사용하여 기본 프로세스 힙에서 할당됩니다. 이 예제에서는 각 힙의 시작 주소를 콘솔에 인쇄합니다. 그런 다음 HeapFree 함수를 사용하여 버퍼에 할당된 메모리를 해제합니다.

프로세스의 힙 수는 다를 수 있습니다. 프로세스에는 항상 하나 이상의 힙(기본 프로세스 힙)이 있으며 애플리케이션 또는 프로세스의 주소 공간에 로드되는 DLL에서 만든 하나 이상의 프라이빗 힙이 있을 수 있습니다.

애플리케이션은 기본 프로세스 힙 또는 애플리케이션이 만든 프라이빗 힙에서만 힙 함수를 호출해야 합니다. 다른 구성 요소가 소유한 프라이빗 힙에서 힙 함수를 호출하면 정의되지 않은 동작이 발생할 수 있습니다.

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

int __cdecl _tmain()
{
    DWORD NumberOfHeaps;
    DWORD HeapsIndex;
    DWORD HeapsLength;
    HANDLE hDefaultProcessHeap;
    HRESULT Result;
    PHANDLE aHeaps;
    SIZE_T BytesToAllocate;

    //
    // Retrieve the number of active heaps for the current process
    // so we can calculate the buffer size needed for the heap handles.
    //
    NumberOfHeaps = GetProcessHeaps(0, NULL);
    if (NumberOfHeaps == 0) {
        _tprintf(TEXT("Failed to retrieve the number of heaps with LastError %d.\n"),
                 GetLastError());
        return 1;
    }

    //
    // Calculate the buffer size.
    //
    Result = SIZETMult(NumberOfHeaps, sizeof(*aHeaps), &BytesToAllocate);
    if (Result != S_OK) {
        _tprintf(TEXT("SIZETMult failed with HR %d.\n"), Result);
        return 1;
    }

    //
    // Get a handle to the default process heap.
    //
    hDefaultProcessHeap = GetProcessHeap();
    if (hDefaultProcessHeap == NULL) {
        _tprintf(TEXT("Failed to retrieve the default process heap with LastError %d.\n"),
                 GetLastError());
        return 1;
    }

    //
    // Allocate the buffer from the default process heap.
    //
    aHeaps = (PHANDLE)HeapAlloc(hDefaultProcessHeap, 0, BytesToAllocate);
    if (aHeaps == NULL) {
        _tprintf(TEXT("HeapAlloc failed to allocate %d bytes.\n"),
                 BytesToAllocate);
        return 1;
    }

    // 
    // Save the original number of heaps because we are going to compare it
    // to the return value of the next GetProcessHeaps call.
    //
    HeapsLength = NumberOfHeaps;

    //
    // Retrieve handles to the process heaps and print them to stdout. 
    // Note that heap functions should be called only on the default heap of the process
    // or on private heaps that your component creates by calling HeapCreate.
    //
    NumberOfHeaps = GetProcessHeaps(HeapsLength, aHeaps);
    if (NumberOfHeaps == 0) {
        _tprintf(TEXT("Failed to retrieve heaps with LastError %d.\n"),
                 GetLastError());
        return 1;
    }
    else if (NumberOfHeaps > HeapsLength) {

        //
        // Compare the latest number of heaps with the original number of heaps.
        // If the latest number is larger than the original number, another
        // component has created a new heap and the buffer is too small.
        //
        _tprintf(TEXT("Another component created a heap between calls. ") \
                 TEXT("Please try again.\n"));
        return 1;
    }

    _tprintf(TEXT("Process has %d heaps.\n"), HeapsLength);
    for (HeapsIndex = 0; HeapsIndex < HeapsLength; ++HeapsIndex) {
        _tprintf(TEXT("Heap %d at address: %#p.\n"),
                 HeapsIndex,
                 aHeaps[HeapsIndex]);
    }
  
    //
    // Release memory allocated from default process heap.
    //
    if (HeapFree(hDefaultProcessHeap, 0, aHeaps) == FALSE) {
        _tprintf(TEXT("Failed to free allocation from default process heap.\n"));
    }

    return 0;
}