MSDN Documentation

Memory APIs

HeapSize

The HeapSize function retrieves the size of a memory block allocated from a heap. It is part of the Windows API and is defined in Heapapi.h.

Syntax

SIZE_T WINAPI HeapSize(
    HANDLE  hHeap,
    DWORD   dwFlags,
    LPCVOID lpMem
);

Parameters

ParameterDescription
hHeapHandle to the heap from which the memory block was allocated.
dwFlagsHeap allocation‑flags. Typically set to 0.
lpMemPointer to the memory block whose size is to be retrieved.

Return Value

Returns the size of the memory block, in bytes. If the function fails, it returns (SIZE_T)‑1. Use GetLastError for extended error information.

Example

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

int main(void)
{
    HANDLE hHeap = GetProcessHeap();
    if (!hHeap) return 1;

    // Allocate 256 bytes
    void *p = HeapAlloc(hHeap, 0, 256);
    if (!p) return 1;

    SIZE_T sz = HeapSize(hHeap, 0, p);
    if (sz == (SIZE_T)-1) {
        printf("HeapSize failed: %lu\\n", GetLastError());
    } else {
        printf("Allocated block size: %zu bytes\\n", sz);
    }

    HeapFree(hHeap, 0, p);
    return 0;
}