Handles, Kernel Objects and the Win32 API Explained
What a Windows HANDLE is, how the per-process handle table refers to kernel objects, how handles are closed, duplicated and inherited, and how to spot leaks.

Open almost any Win32 reference and the same type appears in the signatures: HANDLE. A file is a handle. A process is a handle. A thread, an event, a mutex, a timer, a pipe, a registry key: all handles. Programs that use the API correctly open them, use them and close them. Programs that do not leak them, and a leak on Windows is not abstract: the file stays locked, the child process lingers as an entry in the process table, and the program's handle count climbs until something fails. Understanding what a handle is, and what is behind it, turns a large and apparently inconsistent API into one model with a few rules.
The examples use the Windows 11 SDK (10.0.26100) with MSVC 19.4 on x64. Function details are in the Win32 documentation on Microsoft Learn, in particular the pages for CloseHandle, DuplicateHandle and SetHandleInformation.
The idea: names for things the kernel owns
Some resources must be owned by the operating system. An open file has a position, a lock state and buffers in kernel memory. A process has an address space and a thread list. A mutex has a waiting queue. A program cannot hold these directly, because it could corrupt them, so it holds a handle instead: an opaque value that means "the object with this entry in my table". The kernel looks the value up on each call, checks that the process is allowed to do that operation, and acts.
The structure behind it has two layers. Every process has a handle table, owned by the kernel, in which each entry holds a pointer to a kernel object and the access rights that were granted when the handle was opened. The value your code sees, the HANDLE, is an index into that table. On current Windows the values are multiples of four, so you see numbers such as 0x0000000000000124. The numbers carry no meaning outside the process: handle 0x124 in one process and handle 0x124 in another are different, and usually unrelated, things.
The objects themselves live in the kernel's object manager and are reference counted. Each handle in any process counts as one reference. The object is destroyed when its count falls to zero, which happens after the last handle in every process is closed and the kernel's own references are gone. This is why closing your handle to a running child process does not stop the child, and why a file stays open as long as any process, including one you started, holds a handle to it.
Which things are handles
The kernel objects that Win32 exposes through HANDLE include:
| Object | Created with | Waitable |
|---|---|---|
| File, device, pipe, console | CreateFileW, CreatePipe, CreateNamedPipeW | The overlapped event |
| Process | CreateProcessW, OpenProcess | Yes, signaled at exit |
| Thread | CreateThread, _beginthreadex | Yes, signaled at exit |
| Event | CreateEventW | Yes |
| Mutex | CreateMutexW | Yes |
| Semaphore | CreateSemaphoreW | Yes |
| Waitable timer | CreateWaitableTimerW | Yes |
| File mapping | CreateFileMappingW | No |
| Job object | CreateJobObjectW | Yes |
| Access token | OpenProcessToken | No |
Notice what is not in the list. Window handles (HWND), menu, icon and cursor handles, GDI handles for pens and brushes (HPEN, HBRUSH, HBITMAP), and registry keys (HKEY) are called handles too, and share the idea, but they are managed by other subsystems with their own tables and their own close functions: DestroyWindow, DeleteObject, RegCloseKey. They are not closed with CloseHandle. A window handle passed to CloseHandle fails, and there is no compile-time check, because both are pointer-sized values. Always close a handle with the function its creation documentation names.
The lifecycle
The sequence is the same for every kernel object.
#include <windows.h>
#include <stdio.h>
int wmain(void)
{
HANDLE h = CreateEventW(NULL, TRUE, FALSE, NULL);
if (h == NULL) {
fwprintf(stderr, L"CreateEvent failed: %lu\n", GetLastError());
return 1;
}
SetEvent(h);
DWORD r = WaitForSingleObject(h, 0);
wprintf(L"wait result: %s\n", r == WAIT_OBJECT_0 ? L"signaled" : L"not signaled");
if (!CloseHandle(h))
fwprintf(stderr, L"CloseHandle failed: %lu\n", GetLastError());
return 0;
}cl /nologo /W4 /DUNICODE /D_UNICODE lifecycle.c
lifecycle.exelifecycle.c
wait result: signaledFour steps: create, check, use, close. The check is where handles differ among functions. CreateEventW returns NULL on failure. CreateFileW returns INVALID_HANDLE_VALUE, which is (HANDLE)-1. CreateThread, CreateMutexW, CreateSemaphoreW and CreateFileMappingW return NULL. A program that tests for the wrong sentinel treats a failure as success and later passes garbage to other calls. The documentation of each function has a "Return value" section that settles it.
After CloseHandle, the value in the variable is stale, and using it is a bug. If another thread has meanwhile opened something new, the table slot can be reused, and your stale value then refers to an unrelated object. Setting the variable to NULL or INVALID_HANDLE_VALUE after closing makes such mistakes fail loudly.
Seeing handles and leaks
The kernel keeps the count, and Win32 lets you read it:
#include <windows.h>
#include <stdio.h>
static DWORD count(void)
{
DWORD n = 0;
GetProcessHandleCount(GetCurrentProcess(), &n);
return n;
}
int wmain(void)
{
DWORD before = count();
for (int i = 0; i < 100; i++)
CreateEventW(NULL, FALSE, FALSE, NULL); /* handle ignored: leaked */
DWORD after = count();
wprintf(L"handles before: %lu\n", before);
wprintf(L"handles after: %lu\n", after);
wprintf(L"leaked: %lu\n", after - before);
return 0;
}cl /nologo /W4 /DUNICODE /D_UNICODE leak.c
leak.exeleak.c
handles before: 36
handles after: 136
leaked: 100The starting count depends on the system and on what the runtime opened, so yours will differ, but the difference of 100 is exact: each CreateEventW returned a handle that the program threw away. This is the cheapest leak detector there is. Call GetProcessHandleCount at the start and end of a test, or in a loop, and the number should stabilize. A count that grows with each iteration of a request handler is a leak.
Outside the program, Process Explorer from Sysinternals shows the handle list for any process, with the type and name of each object, and highlights newly opened ones. The Task Manager's Details tab can show a Handles column. A process that approaches the per-process limit, which is 16 million, fails in strange ways long before it gets there, because kernel memory for the objects is consumed.
What closing does and does not do
CloseHandle removes one handle table entry and drops one reference. It does not stop a process, cancel a thread or abort an operation. For a thread, closing the handle just says "I do not need to wait for it", and the thread keeps running. For a process, closing the handle leaves the child running. For a file, closing it flushes nothing extra: data written with WriteFile is in the file system cache and will be written eventually, and FlushFileBuffers is the call that forces it out.
Closing a handle that is still in use by another thread, for example while that thread is blocked in ReadFile on it, is a classic race. The result depends on the object, but the least bad case is a failed operation and the worst is the stale-value problem above. Arrange for the thread to stop before the owner closes the handle.
Duplicating and sharing
A handle is local to a process, but you often need to give one to another. There are three mechanisms.
Inheritance. When you create an object with a SECURITY_ATTRIBUTES structure whose bInheritHandle is TRUE, or set the flag later with SetHandleInformation(h, HANDLE_FLAG_INHERIT, HANDLE_FLAG_INHERIT), the handle is marked inheritable. A child created with CreateProcess and bInheritHandles = TRUE receives a copy at the same numeric value. This is how a parent redirects a child's standard output to a pipe.
Duplication. DuplicateHandle copies a handle, within a process or into another, and can reduce the access rights while doing so.
#include <windows.h>
#include <stdio.h>
int wmain(void)
{
HANDLE ev = CreateEventW(NULL, TRUE, FALSE, NULL);
HANDLE copy = NULL;
if (!DuplicateHandle(GetCurrentProcess(), ev,
GetCurrentProcess(), ©,
0, FALSE, DUPLICATE_SAME_ACCESS)) {
fwprintf(stderr, L"DuplicateHandle failed: %lu\n", GetLastError());
return 1;
}
wprintf(L"different values: %s\n", ev != copy ? L"yes" : L"no");
SetEvent(copy); /* signals the same object */
wprintf(L"original is signaled: %s\n",
WaitForSingleObject(ev, 0) == WAIT_OBJECT_0 ? L"yes" : L"no");
CloseHandle(copy); /* object survives */
wprintf(L"after closing the copy, still valid: %s\n",
SetEvent(ev) ? L"yes" : L"no");
CloseHandle(ev);
return 0;
}different values: yes
original is signaled: yes
after closing the copy, still valid: yesTwo handles with different values refer to one event. The object has two references, and it lives until both are closed. This is also the way to turn a pseudo handle into a real one. GetCurrentProcess() and GetCurrentThread() do not return table entries: they return the constants (HANDLE)-1 and (HANDLE)-2, which every process interprets as "myself". They need no closing, they cannot be handed to another process, and a thread that stores GetCurrentThread() and passes it to a second thread has stored a reference to the wrong thread. Use DuplicateHandle on the pseudo handle to get a real one.
Names. Many objects can be created with a name, such as an event created with CreateEventW and a name argument that starts with the prefix Local. Another process opens the same object by the same name with OpenEventW, getting its own handle. Names live in a namespace. A name beginning with Local is private to the current logon session, one with Global is system wide and typically needs privileges to create from a service, and a name with neither goes in the session's namespace by default. Two unrelated programs that choose the same name collide, so use a name unlikely to repeat, such as a GUID.
Access rights
A handle records what you may do with the object, decided when you open it and checked against the object's security descriptor. A file opened with GENERIC_READ cannot be written. A process handle from OpenProcess(PROCESS_QUERY_LIMITED_INFORMATION, ...) can be queried but not terminated. Asking for more than you need is the usual reason a call fails with ERROR_ACCESS_DENIED on an object you can read but not write.
The principle is the same as least privilege: ask for exactly the rights the program uses. Opening another process with PROCESS_ALL_ACCESS fails against protected processes, and the same code with only the rights actually needed often works.
Handles and the wait functions
Handles to waitable objects are what WaitForSingleObject and WaitForMultipleObjects accept. A kernel object has a signaled or non-signaled state whose meaning depends on its type, and the wait functions block until the state is signaled. This unifies waiting: one call can wait for a process to exit, a thread to finish, an event to be set, and a timer to fire, all together. That unification is the strongest practical reason for the handle model, and it is what makes event-driven structure in Win32 programs natural. The post on waiting covers the details.
Common mistakes
Leaking on error paths. A function that opens three handles and returns early after the second leaks the first two. Structure the function with a single cleanup block, or close in reverse order on every exit.
Closing a handle twice. The second CloseHandle fails with ERROR_INVALID_HANDLE, or worse, closes a different object that reused the slot. Under a debugger with Application Verifier enabled, a double close raises an exception at the point of the second call, which is how it is usually found.
Using the wrong close function. FindClose for FindFirstFile handles, RegCloseKey for registry keys, FreeLibrary for modules, UnmapViewOfFile for mapped views. CloseHandle on those is wrong.
**Forgetting the thread and process handles from CreateProcess.** The call returns both in PROCESS_INFORMATION, and both must be closed. This is the most common leak in programs that launch other programs.
Inheriting too much. Marking handles inheritable and creating children with bInheritHandles = TRUE passes every inheritable handle to the child, including ones that should be private, such as a lock file. Use a process thread attribute list with PROC_THREAD_ATTRIBUTE_HANDLE_LIST to pass exactly the handles you intend.


