Is "CloseHandle(0)" always safe? RRS feed

  • Question

  • Is "CloseHandle(-1)" always safe?

    Is "CloseHandle(0)" always safe?

    Any existing handle can't be 0 and -1?


    Sunday, March 11, 2012 6:21 AM


  • To be honest I wouldn't risk anything.

    First of all, CloseHandle(-1) is never safe. The current implementation has the current process pseudo handle as -1, and the CloseHandle documentation says

    "If the application is running under a debugger, the function will throw an exception if it receives either a handle value that is not valid or a pseudo-handle value."

    the documentation also says

    "It is usually not necessary to call CloseHandle if a function that uses a handle fails with ERROR_INVALID_HANDLE, because this error usually indicates that the handle is already invalidated."

    so never do CloseHandle(-1).

    For CloseHandle(0) again, the NULL handle is usually used to show that a function failed, but from what I remember there is nothing documenting that 0 will never be used for a kernel object handle. Right now I think it is all implementation details.

    Anyway, the CloseHandle documentation says

    "Generally, an application should call CloseHandle once for each handle it opens."

    so follow this advice. Don't assume that like free() or delete there is a safe value that will always work (there is nothing documenting this at all) and just stick to closing only the handles you successfully open, and then only close it once.

    This is a signature

    Any samples given are not meant to have error checking or show best practices. They are meant to just illustrate a point. I may also give inefficient code or introduce some problems to discourage copy/paste coding. This is because the major point of my posts is to aid in the learning process.

    Do you want Visual Studio 11 Express to be freely installable on Windows 7 and able to write regular C++ applications? Please vote for this.

    • Marked as answer by Mike Dos Zhang Wednesday, March 14, 2012 10:51 AM
    Sunday, March 11, 2012 5:58 PM