Thursday, November 10, 2005

oversee CloseHandle

there are many WinAPI functions which create and return a HANDLE object, like CreateThread, CreateFile.
in windows header file, a HANDLE is defined like this
typedef void* HANDLE

doing a 'CloseHandle' more than it is needed on the same HANDLE value is as bad as doing 'delete' on the same pointer.
the docs say:
"CloseHandle invalidates the specified object handle, decrements the object's handle count, and performs object retention checks. After the last handle to an object is closed, the object is removed from the system."
so as long as the handle count is not zero, its logic of course to call CloseHandle.

there are few considerations with the HANDLE objects:
- some functions are not requiring to do CloseHandle on the their returned HANDLE object; so always, always read the docs; dont rely on the fact you are an experienced WinAPI programmer; the behaviour might be (it is !) different between functions (in fact you can find an example in the John Robbins book, Debugging Windows);
- doing a CloseHandle on an object which is invalid it may be disastrous;
Once, my CloseHandle hit a memory location where a CString was living;

No comments:

Post a Comment