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.
SIZE_T WINAPI HeapSize(
HANDLE hHeap,
DWORD dwFlags,
LPCVOID lpMem
);
| Parameter | Description |
|---|---|
hHeap | Handle to the heap from which the memory block was allocated. |
dwFlags | Heap allocation‑flags. Typically set to 0. |
lpMem | Pointer to the memory block whose size is to be retrieved. |
Returns the size of the memory block, in bytes. If the function fails, it returns (SIZE_T)‑1. Use GetLastError for extended error information.
#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;
}