Question

I have a large old program which has some rather complex graphical displays (all via standard API calls). The program appears to be working fine, but I recently looked at the "handles" field of Windows Task Manager when this program was running and noticed that the number of handles was gradually and relentlessly creeping upwards.

Is there some software or strategy I can employ to trace this rogue handle creation?

I Would expect the program to create a large number of handles, but I would also expect this to reach a limit. So what I really want to see is which part of the code was creating the most recent handles.

EDIT: After some investigation with "Process Explorer" I have discovered that the thing that is creeping up is "Handles" rather then "GDI Handles". So I guess that means its nothing to do with the complex graphics.

Was it helpful?

Solution

Please try this link for advice. Problem is complex and somebody has written tutorial on how to tackle it. Update: here is one more link that can help.

OTHER TIPS

The best way to handle this problem is to use the RAII design pattern.

In which for every handle you create you wrap it in a class.

For example:

class CAutoHandle
{
public:
  CAutoHandle(HANDLE handle) : m_handle(handle)
  {
  }

  ~CAutoHandle()
  {
    CloseHandle(m_handle);
  }

  HANDLE m_handle;
};

@JaredPar also suggests another solution here in which you redefine CreateFile to call your own function that has tracking.

You can use Memory Validator to find the handles leak. Try Eval version.

Handles can be a lot of things, not just file handles but also GUI objects (quirks like creating an icon and deleting it with DeleteObject() rather than DestroyIcon()).

There's an MSDN article with various techniques: http://msdn.microsoft.com/en-us/magazine/cc301756.aspx and a program package called Leaks.exe (assuming that you still can run your code under W95)

Other functions that create HANDLEs are CreateThread, OpenThread, CreateProcess, OpenProcess, CreateMutex, OpenMutex, LoadLibrary and possibly InitializeCriticalSection (not sure about that one).

I don't know if these qualify as event handles in that tool which you are using but they may be worth checking.

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