Example (_heap_walk -- Return Information about Default Heap)

This example allocates some memory, then uses _heap_walk to walk the heap and pass information about allocated objects to the callback function callback_function. callback_function then checks the information and keeps track of the number of allocated objects.

#include <stdlib.h>
#include <stdio.h>
#include <malloc.h>
int _Optlink callback_function(const void *pentry, size_t sz, int useflag,
                               int status, const char *filename, size_t line)
{
   if (_HEAPOK != status) {
      puts("status is not _HEAPOK.");
      exit(status);
   }
   if (_USEDENTRY == useflag)
      printf("allocated  %p     %u\n", pentry, sz);
   else
      printf("freed      %p     %u\n", pentry, sz);
   return 0;
}
int main(void)
{
   char  *p1, *p2, *p3;
   if (NULL == (p1 = (char*)malloc(100)) ||
       NULL == (p2 = (char*)malloc(200)) ||
       NULL == (p3 = (char*)malloc(300))) {
      puts("Could not allocate memory block.");
      exit(EXIT_FAILURE);
   }
   free(p2);
   puts("usage      address   size\n-----      -------   ----");
   _heap_walk(callback_function);
   free(p1);
   free(p3);
   return 0;
   /***************************************************************
      The output should be similar to:
      usage      address   size
      -----      -------   ----
      allocated  73A10     300
      allocated  738B0     100
       :
       :
      freed      73920     224
   ***************************************************************/
}