Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Free a Windows heap without releasing memory pages

I'm implementing a heap pool utility and I need a pool_clear() function (like Apache Portable Runtime apr_pool_clear()). This functions allow us to free at once (single function call) all memory allocated on that pool without releasing memory pages to underlying system. Windows API only provides HeapFree() (multiple function calls) and HeapDestroy() (releases memory pages).

Are there any way to do it on Windows (using native API)?

like image 719
user3368561 Avatar asked Dec 13 '25 01:12

user3368561


1 Answers

HeapCreate and other Heap* functions from Kernel32 don't provide this kind of power. They are meant to provide the same functionality as the C Standard Library, plus some extra debugging/diagnostic features.

It sounds like RtlCreateHeap from ntdll would fit the bill, allocating the memory yourself and specifying a HeapBase, InitialCommit, InitialReserve, and CommitRoutine.

This means that you can call RtlDestroyHeap without it giving back all of the virtual memory, then, call RtlCreateHeap again with the same HeapBase, effectively, creating a new heap in the same virtual memory

Unfortunately, to my knowledge, these entry points in ntdll are undocumented, as is most of the Native API, so there is a risk associated with calling it. The linked documentation is for the entry point in Ntoskrnl for drivers to use. Since you explicitly call out using the Native API, maybe you understand and accept this sort of risk. In any case, it would almost certainly be safer to use a library that has already implemented this functionality.

If you are really serious about this sort of thing (which, frankly, scares me), you'll definitely want to look at ReactOS's heap implementation as a supplement to Microsoft's documentation.

like image 140
Sean Cline Avatar answered Dec 16 '25 22:12

Sean Cline