Example (_uclose -- Close Heap from Use)

This example creates and opens a heap, and then performs operations on it. It then calls _uclose to close the heap before destroying it.

#if  (1 == __TOS_OS2__)          /* For OS/2 */
     #define  INCL_DOSMEMMGR     /* Memory Manager values */
     #include <os2.h>
     #include <bsememf.h>        /* Get flags for memory management */
#else
     #include <windows.h>        /* For Windows */
#endif
#include <stdlib.h>
#include <stdio.h>
#include <umalloc.h>
#include <string.h>
int main(void)
{
   void    *initial_block;
   Heap_t  myheap;
   char    *p;
#if  (1 == __TOS_OS2__)
   APIRET  rc;
   /* 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);
#else
   /* Call VirtualAlloc to get the initial block of memory */
   if (NULL == (initial_block =
       VirtualAlloc(NULL, 65536, MEM_COMMIT|MEM_RESERVE, PAGE_READWRITE)))
   {
      printf("VirtualAlloc error: %d\n", GetLastError());
#endif
      exit(EXIT_FAILURE);
   }
   /* Create a fixed size heap starting with the block declared earlier */
   if (NULL == (myheap = _ucreate(initial_block, 65536, _BLOCK_CLEAN,
                                  _HEAP_REGULAR, NULL, NULL))) {
      puts("_ucreate failed.");
      exit(EXIT_FAILURE);
   }
   if (0 != _uopen(myheap)) {
      puts("_uopen failed.");
      exit(EXIT_FAILURE);
   }
   p = (char *)_umalloc(myheap, 100);
   memset(p, 'x', 10);
   free(p);
   if (0 != _uclose(myheap)) {
      puts("_uclose failed");
      exit(EXIT_FAILURE);
   }
#if  (1 == __TOS_OS2__)
   if (0 != (rc = DosFreeMem(initial_block)))
   {
      printf("DosFreeMem error: return code = %ld\n", rc);
#else
   if (FALSE == (VirtualFree(initial_block, 0, MEM_RELEASE)))
   {
      printf("VirtualFree error: %d.\n", GetLastError());
#endif
      exit(EXIT_FAILURE);
   }
   return 0;
}