regardless of how you create the kernel object, indicate to the system that you will end the operation of the object by calling CloseHandle:
BOOL CloseHandle (HANDLE hobj);
The function first checks the handle table of the calling process to ensure that the index (handle) passed to it is used to identify an object that the process does not actually have permission to access. If the index is valid, the system can obtain the address of the kernel object's data structure and determine the data members of the usage count in the structure. If the usage count is 0, the kernel will revoke the kernel object from memory.
If you pass an invalid handle to CloseHandle, one of two things will happen. If the process is working correctly, CloseHandle returns FALSE, and GetLastError returns ERROR_INVALID_HANDLE. If the process is troubleshooting an error, the system notifies the debugger so that it can be excluded from the error.
before CloseHandle returns, it clears the item in the handle table of the process, which is now invalid for your process and should not attempt to use it. The purge operation occurs regardless of whether the kernel object has been undone. When the CloseHandle function is called, access to the kernel object is no longer available, but if the object's usage count is not decremented to 0, the object has not been undone. This is no problem, it simply means that one or more other processes are using the object. When another process stops using the object (by calling CloseHandle), the object is undone.
If you forget to call the CloseHandle function, will there be a memory leak? The answer is possible, but not necessarily. Processes can potentially leak resources (such as kernel objects) while the process is running. However, it is guaranteed that the operating system can ensure that any or all resources used by the process are freed when the process terminates. For kernel objects, the system performs the following actions: When the process terminates, the process's handle table is automatically scanned. If the table has any invalid items (that is, objects that are not closed before the process is terminated), the system closes these object handles. If the usage count of any object in these objects is reduced to 0, the kernel undoes the object.
As a result, the application may leak kernel objects at run time, but when the process terminates, the system will be able to ensure that everything is properly purged. In addition, this applies to all objects, resources, and blocks of memory, that is, when the process terminates, the system guarantees that the process will not leave any objects behind.
Windows core Programming (5th Edition)----shutting down kernel objects