HeapFree Function
The HeapFree function deallocates a memory block that was allocated by the HeapAlloc or HeapReAlloc function.
Syntax
BOOL HeapFree(
HANDLE hHeap,
DWORD dwFlags,
LPVOID lpMem
);
Parameters
hHeap
- A handle to the heap that was created by a call to the HeapCreate function. This handle is passed to the HeapAlloc or HeapReAlloc function.
dwFlags
-
Flags that control the deallocation of the memory block. The following flag is currently defined:
- HEAP_NO_SERIALIZATION (0x00000001): If this value is specified, the memory allocation functions on this heap will not be protected by a mutex. This can increase the speed of the functions at the cost of the function's security on multiple threads. In this case, you must synchronize all threads that are using the heap.
lpMem
-
A pointer to the memory block to be freed. This pointer is returned by a previous call to HeapAlloc or HeapReAlloc. If
lpMem
is NULL, the function does nothing.
Return Value
If the function succeeds, the return value is TRUE.
If the function fails, the return value is FALSE. To get extended error information, call GetLastError.
Remarks
To free a memory block allocated by HeapAlloc or HeapReAlloc, use HeapFree. Do not use the free function.
Important: If the heap was created with the HEAP_NO_SERIALIZATION flag, you must ensure that threads do not access the heap concurrently when you call HeapFree.
When a memory block is freed, its size is added to the size of the specified heap.
The following example code demonstrates how to allocate and then free a memory block using HeapAlloc
and HeapFree
.
#include <windows.h>
#include <iostream>
int main() {
// Create a heap
HANDLE hHeap = HeapCreate(0, 1024 * 1024, 0); // 1MB initial, no max size
if (hHeap == NULL) {
std::cerr << "Failed to create heap. Error: " << GetLastError() << std::endl;
return 1;
}
// Allocate memory from the heap
SIZE_T allocationSize = 128;
LPVOID pMemory = HeapAlloc(hHeap, 0, allocationSize);
if (pMemory == NULL) {
std::cerr << "Failed to allocate memory. Error: " << GetLastError() << std::endl;
HeapDestroy(hHeap); // Clean up heap
return 1;
}
std::cout << "Memory allocated successfully at: " << pMemory << std::endl;
// Use the allocated memory...
// For example:
// char* data = static_cast<char*>(pMemory);
// strcpy_s(data, allocationSize, "Hello, Windows API!");
// Free the allocated memory
if (HeapFree(hHeap, 0, pMemory)) {
std::cout << "Memory freed successfully." << std::endl;
} else {
std::cerr << "Failed to free memory. Error: " << GetLastError() << std::endl;
}
// Destroy the heap
if (HeapDestroy(hHeap)) {
std::cout << "Heap destroyed successfully." << std::endl;
} else {
std::cerr << "Failed to destroy heap. Error: " << GetLastError() << std::endl;
}
return 0;
}
Requirements
Minimum supported client | Windows XP |
Minimum supported server | Windows Server 2003 |
Header | Winbase.h |
Library | Kernel32.lib |
DLL | Kernel32.dll |