Why does my windows console application leak when idling? (And why does the smoking gun point at kernel32.dll??)

StackOverflow https://stackoverflow.com/questions/2206930

Question

I have a windows multi-threded console application that appears to be leaking approximately 4kb private memory every minute or so.

In an effort to localise the leak, I have gradually suspended each thread in the application until the leak stopped, and to my surprise the culprit seems to be a thread named "Win32Thread".

It does not look like a thread I have explicitly started.

If I attach and break the application, the stack trace looks like this:

    ntdll.dll!_KiFastSystemCallRet@0()  
    ntdll.dll!_NtCancelTimer@8()  + 0xc bytes   
    ntdll.dll!_RtlpResetTimer@12()  + 0x15 bytes    
>   ntdll.dll!_RtlpServiceTimer@12()  + 0xfd bytes  
    ntdll.dll!_KiUserApcDispatcher@16()  + 0x25 bytes   
    kernel32.dll!_BaseThreadStart@8()  + 0x34 bytes 

Does anyone have any idea why this would suddenly leak?

The application as been running for about a 40hrs on a Win2k3 SP2 dual core system.

Any ideas are greately appreciated.

Was it helpful?

Solution

That stack trace looks like it's in code related to timers. I'd guess that your code (or a library you use) started a timer by using timeSetEvent or a similar function. In that case, the leak would probably be in your timer callback function.

Starting a multimedia timer causes a thread to be created, and your callback will be called from that thread. A periodic timer would explain why it leaks while idling.

OTHER TIPS

Does your application have any APCs (Asynchronous procedure calls) or scheduled timer events? Multimedia timer callbacks would.

If your callback uses C runtime calls, these calls makes one-off thread local allocations (lazily, allocated first time the function is called in a thread) to do their work (_tcstol, sprintf etc). Because the thread was not started with beginthread() or beginthreadex() this memory can't be cleaned up when the thread dies, so that would manifest as a leak.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top