Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Detect file handle leaks with Win32 C++

Is there some way to detect file handle leaks at program termination?

In particular I would like to make sure that all of my handles that get created are being freed in code.

For example, I may have a CreateFile() somewhere, and at program termination I want to detect and ensure that all of them are closed.

like image 226
Brian R. Bondy Avatar asked Nov 24 '08 20:11

Brian R. Bondy


2 Answers

If you can (i.e. if it's not a huge legacy code-base you are bugfixing) you should consider using the RAII idiom to wrap around your file handles. By "taking" the file handle in the constructor and releasing it in the destructor you can be sure that by the time your RAII goes out of scope your file handle is nicely cleaned up too.

It's the same principle as smart pointers, and it's a very useful concept to have in your toolbox for avoiding issues like this in C++.

like image 73
Joris Timmermans Avatar answered Oct 17 '22 12:10

Joris Timmermans


I have used !htrace command of windbg.

!htrace -enable
!htrace -snapshot
!htrace -diff

Allow you to compare the handle situation of two execution point and help you the locate the point where the leaked handle have been allocated.

It worked well for me.

like image 26
Vivian De Smedt Avatar answered Oct 17 '22 12:10

Vivian De Smedt