Click here to Skip to main content
Click here to Skip to main content

Tagged as

Terminate a hanging thread

, 16 Jan 2012 CPOL
Rate this:
Please Sign up or sign in to vote.
How to avoid memory leak in WinXP, if you kill a thread

I wrote some code to display all open handles in the system. This is usually a device driver job, but I wrote a workaround for it... The problem was only that my thread was hanging occasionally in an undocumented API. Wink | ;)

It wasn't a problem to kill this thread and create another one, but in WinXP this generates a memory leak: The stack isn't freed via TerminateThread(). This doesn't happen in Vista and newer systems.

Therefore I used another undocumented API:

typedef	VOID (WINAPI *PRtlFreeUserThreadStack)(HANDLE hProcess, HANDLE hThread);
static PRtlFreeUserThreadStack RtlFreeUserThreadStack=NULL;
HMODULE NTLibrary = GetModuleHandleW(L"ntdll.dll");
RtlFreeUserThreadStack = (PRtlFreeUserThreadStack)GetProcAddress(NTLibrary, "RtlFreeUserThreadStack");

The nice thing is, that RtlFreeUserThreadStack() is only available in WinXP and older systems. Therefore the rule is: Use it, if it is available.

void KillThread(HANDLE threadHandle)
   DWORD dwExitCode;
   GetExitCodeThread(threadHandle, &dwExitCode); // check again
   if(dwExitCode == STILL_ACTIVE)
      if(RtlFreeUserThreadStack != NULL)
         RtlFreeUserThreadStack(GetCurrentProcess(), threadHandle);
      TerminateThread(threadHandle, 0); 


This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)


About the Author


Germany Germany
No Biography provided

Comments and Discussions

GeneralRe: Since you've suggested that, I started a blog off and have p... Pinmembernicklowe5-Jan-12 7:36 
GeneralReason for my vote of 4 Nearly correct, but needs to suspend... PinmemberN1CKLAD4-Jan-12 15:31 
GeneralRe: Thanks for your comment and vote. Yes, you are right, but in... Pinmembertrotwa5-Jan-12 3:54 
GeneralReason for my vote of 5 I've never tried this or heard of Rt... PinmemberAlbert Holguin2-Dec-11 8:52 
Reason for my vote of 5
I've never tried this or heard of RtlFreeUserThreadStack, but if it does work, this is a good tip.

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.

| Advertise | Privacy | Terms of Use | Mobile
Web01 | 2.8.141220.1 | Last Updated 16 Jan 2012
Article Copyright 2011 by trotwa
Everything else Copyright © CodeProject, 1999-2014
Layout: fixed | fluid