The following example creates a heap myheap, and then uses _uaddmem to add memory to 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>
int main(void)
{
void *initial_block, *extra_chunk;
Heap_t myheap;
char *p1, *p2;
#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 for initial block failed: 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 for initial block failed: %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);
}
p1 = (char*)_umalloc(myheap, 100);
#if (1 == __TOS_OS2__)
/* Call DosAllocMem to get another block of memory */
if (0 != (rc = DosAllocMem(&extra_chunk, 10 * 65536,
PAG_WRITE | PAG_READ | PAG_COMMIT)))
{
printf("DosAllocMem for extra chunk failed: return code = %ld\n", rc);
#else
/* Call VirtualAlloc to get another block of memory */
if (NULL == (extra_chunk =
VirtualAlloc(NULL, 10 * 65536, MEM_COMMIT|MEM_RESERVE, PAGE_READWRITE)))
{
printf("VirtualAlloc for extra chunk failed: %d.\n", GetLastError());
#endif
exit(EXIT_FAILURE);
}
/* Add the second chunk of memory to user heap */
if (myheap != _uaddmem(myheap, extra_chunk, 10 * 65536, _BLOCK_CLEAN)) {
puts("_uaddmem failed.");
exit(EXIT_FAILURE);
}
p2 = (char*)_umalloc(myheap, 100000);
free(p1);
free(p2);
if (0 != _uclose(myheap)) {
puts("_uclose failed");
exit(EXIT_FAILURE);
}
#if (1 == __TOS_OS2__)
if (0 != DosFreeMem(initial_block) || 0 != DosFreeMem(extra_chunk))
{
puts("DosFreeMem error.");
#else
if (FALSE == VirtualFree(initial_block, 0, MEM_RELEASE) ||
FALSE == VirtualFree(extra_chunk, 0, MEM_RELEASE))
{
puts("VirtualFree error.");
#endif
exit(EXIT_FAILURE);
}
return 0;
}