Reputation: 347
How can I free the virtual memory that is left up after calling TerminateThread
? Can it be done via VirtualFree
and how of course. I fully understand the "Dangers" of TerminateThread
.
Upvotes: 0
Views: 958
Reputation: 612794
In an unmanaged process, there's no realistic way to tidy up memory from the outside.
Memory can be allocated in many different ways. Ultimately it all starts with calls to VirtualAlloc
, VirtualAllocEx
etc. But in practice runtime libraries invariably use sub allocating heap managers. These heap allocators will get memory by calls to VirtualAlloc
, but then will hand out sub-blocks. And heap managers are generally shared between threads in a process. So you've no way from the outside of knowing how to free those sub-blocks.
And even if we did not have sub-allocators, how could you know which blocks handed out by VirtualAlloc
you were allowed to destroy? A thread may allocate memory with a call to VirtualAlloc
and require that the memory out lives the allocating thread and is destroyed by another thread.
But if you are happy to let all of that go, and just want the stack to be destroyed (as per your comments), then this article shows you how to do so with RtlFreeUserThreadStack
: http://www.nicklowe.org/2012/01/thread-termination-dont-leak-the-stack/
Upvotes: 4