The Process Tool Help Library 7

 

 

 

 

 

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.

 

Traversing the Heap List Program Example: Creating new Win32 empty console mode application project

 

Then, add the source file and give it a suitable name.

 

Traversing the Heap List Program Example: Adding new C++ source file to the existing VC++ project

 

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 (L"CreateToolhelp32Snapshot 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(L"Block size: %d\n", he.dwBlockSize );

              

               he.dwSize = sizeof(HEAPENTRY32);

            } while( Heap32Next(&he) );

                  wprintf(L"Press any key for more...\n");

      getwchar();

         }

         hl.dwSize = sizeof(HEAPLIST32);

      } while (Heap32ListNext( hHeapSnap, &hl ));

     

      wprintf(L"Press any key for more...\n");

 

      getwchar();

   }

   else

         wprintf(L"Cannot list first heap (%d)\n", GetLastError());

  

   CloseHandle(hHeapSnap); 

}

 

Build and run the project. The following screenshot is a sample output.

 

Traversing the Heap List Program Example: A sample console program output

 

The Tool Help Reference

 

The following functions and structures are associated with the tool help library.

 

  1. Tool Help Functions
  2. Tool Help Structures

 

 

 

 

< Windows Process Tool Help APIs 6 | Windows Process Tool Help APIs | Win32 Programming | Windows Station and Desktop >