Platform SDK: Memory

HeapCompact

The HeapCompact function attempts to compact a specified heap. It compacts the heap by coalescing adjacent free blocks of memory and decommitting large free blocks of memory.

UINT HeapCompact(
  HANDLE hHeap,  // handle to heap
  DWORD dwFlags  // heap access options
);

Parameters

hHeap
[in] Handle to the heap that the function will attempt to compact.
dwFlags
[in] Specifies heap access during function operation. This parameter can be the following value.
Value Meaning
HEAP_NO_SERIALIZE Specifies that mutual exclusion will not be used while the HeapCompact function accesses the heap.

Return Values

If the function succeeds, the return value is the size, in bytes, of the largest committed free block in the heap. This is an unsigned integer value.

If the function fails, the return value is zero. To get extended error information, call GetLastError.

In the unlikely case that there is absolutely no space available in the heap, the function return value is zero, and GetLastError returns the value NO_ERROR.

Remarks

There is no guarantee that an application can successfully allocate a memory block of the size returned by HeapCompact. Other threads or the commit threshold might prevent such an allocation.

Serialization ensures mutual exclusion when two or more threads attempt to simultaneously allocate or free blocks from the same heap. There is a small performance cost to serialization, but it must be used whenever multiple threads allocate and free memory from the same heap. Setting the HEAP_NO_SERIALIZE value eliminates mutual exclusion on the heap. Without serialization, two or more threads that use the same heap handle might attempt to allocate or free memory simultaneously, likely causing corruption in the heap. The HEAP_NO_SERIALIZE value can, therefore, be safely used only in the following situations:

Note  To guard against an access violation, use structured exception handling to protect any code that writes to or reads from a heap. For more information on structured exception handling with memory accesses, see Reading and Writing and Structured Exception Handling.

Requirements

  Windows NT/2000: Requires Windows NT 3.5 or later.
  Windows 95/98: Unsupported.
  Header: Declared in Winbase.h; include Windows.h.
  Library: Use Kernel32.lib.

See Also

Memory Management Overview, Memory Management Functions, HeapCreate, HeapValidate