Example (_udestroy -- Destroy a Heap) (OS/2)

This example creates and opens a heap, performs operations on it, and then closes it. The program then calls _udestroy with the _FORCE parameter to force the destruction of the heap. _udestroy calls release_fn to return the memory to the system.

#define INCL_DOSMEMMGR                         /* Memory Manager values */
#include <os2.h>
#include <bsememf.h>                 /* Get flags for memory management */
#include <stdlib.h>
#include <stdio.h>
#include <umalloc.h>
static void *get_fn(Heap_t usrheap, size_t *length, int *clean)
{
    void *p;
    /* Round up to the next chunk size */
    *length = ((*length) / 65536) * 65536 + 65536;
    *clean = _BLOCK_CLEAN;
    DosAllocMem(&p, *length, PAG_COMMIT | PAG_READ | PAG_WRITE);
    return (p);
}
static void release_fn(Heap_t usrheap, void *p, size_t size)
{
    DosFreeMem(p);
    return;
}
int main(void)
{
   void    *initial_block;
   APIRET  rc;
   Heap_t  myheap;
   char    *ptr;
   /* Call DosAllocMem to get the initial block of memory */
   if (0 != (rc = DosAllocMem(&initial_block, 65536,
                              PAG_WRITE | PAG_READ | PAG_COMMIT))) {
      printf("DosAllocMem error: return code = %ld\n", rc);
      exit(EXIT_FAILURE);
   }
   /* Create an expandable heap starting with the block declared earlier */
   if (NULL == (myheap = _ucreate(initial_block, 65536, _BLOCK_CLEAN,
                                  _HEAP_REGULAR, get_fn, release_fn))) {
      puts("_ucreate failed.");
      exit(EXIT_FAILURE);
   }
   if (0 != _uopen(myheap)) {
      puts("_uopen failed.");
      exit(EXIT_FAILURE);
   }
   /* Force user heap to grow */
   ptr = _umalloc(myheap, 100000);
   _uclose(myheap);
   if (0 != _udestroy(myheap, _FORCE)) {
      puts("_udestroy failed.");
      exit(EXIT_FAILURE);
   }
   if (0 != (rc = DosFreeMem(initial_block))) {
      printf("DosFreeMem error: return code = %ld\n", rc);
      exit(EXIT_FAILURE);
   }
   return 0;
}