If you can't afford BoundsChecker or similar...
One trick I've used is to replace CreateFile
etc. with my own wrappers. In addition to returning the handle value, they make a record of the __FILE__ and __LINE__ to go with each handle. You'll need to wrap CloseHandle
as well, to make sure that properly-closed handles don't raise false positives.
It's as simple as:
// StdAfx.h
#include <windows.h>
#undef CreateFile
#if defined(UNICODE)
#define CreateFile DbgCreateFileW
#else
#define CreateFile DbgCreateFileA
#endif
// etc.
You then define DbgCreateFileW
and DbgCreateFileA
somewhere in your code.
This assumes that you've got control over the relevant pieces of code. If not, you can do something similar by using (e.g.) Microsoft Detours (you'll need a license to include it in a released product, but I believe that it's free to use for debugging/testing/etc.)
Long term, however, you should look at converting your code to use a "smart" handle type that automatically calls CloseHandle
when it goes out of scope.