This example uses _ucreate to create an expandable heap. The functions for expanding and shrinking the heap are get_fn and release_fn. The program then opens the heap and performs operations on it, and then closes and destroys the heap.
#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 | PAGE_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 DosAllenMem 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;
}