Traversing the Heap List Program Example
The following example obtains a list of heaps for the current process. It takes a snapshot of the heaps using the CreateToolhelp32Snapshot() function, and then walks through the list using the Heap32ListFirst() and Heap32ListNext() functions. For each heap, it uses the Heap32First() and Heap32Next() functions to walk the heap blocks.
Create a new empty Win32 console application project. Give a suitable project name and change the project location if needed.
Then, add the source file and give it a suitable name.
Next, add the following source code.
#include <windows.h>
#include <tlhelp32.h>
#include <stdio.h>
int wmain(int argc, WCHAR *argv[])
{
HEAPLIST32 hl;
HANDLE hHeapSnap = CreateToolhelp32Snapshot(TH32CS_SNAPHEAPLIST, GetCurrentProcessId());
hl.dwSize = sizeof(HEAPLIST32);
if ( hHeapSnap == INVALID_HANDLE_VALUE )
{
wprintf (LCreateToolhelp32Snapshot failed (%d)\n, GetLastError());
return 1;
}
if( Heap32ListFirst( hHeapSnap, &hl ) )
{
do
{
HEAPENTRY32 he;
ZeroMemory(&he, sizeof(HEAPENTRY32));
he.dwSize = sizeof(HEAPENTRY32);
if( Heap32First( &he, GetCurrentProcessId(), hl.th32HeapID ) )
{
wprintf(L\nHeap ID: %d\n, hl.th32HeapID );
do
{
wprintf(LBlock size: %d\n, he.dwBlockSize );
he.dwSize = sizeof(HEAPENTRY32);
} while( Heap32Next(&he) );
wprintf(LPress any key for more...\n);
getwchar();
}
hl.dwSize = sizeof(HEAPLIST32);
} while (Heap32ListNext( hHeapSnap, &hl ));
wprintf(LPress any key for more...\n);
getwchar();
}
else
wprintf(LCannot list first heap (%d)\n, GetLastError());
CloseHandle(hHeapSnap);
}
Build and run the project. The following screenshot is a sample output.
The Tool Help Reference
The following functions and structures are associated with the tool help library.