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.
#include <windows.h> #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;
p = VirtualAlloc(NULL, *length, MEM_COMMIT|MEM_RESERVE, PAGE_READWRITE);
return (p);
}
static void release_fn(Heap_t usrheap, void *p, size_t size)
{
VirtualFree(p, 0, MEM_RELEASE );
return;
}
int main(void)
{
void *initial_block;
Heap_t myheap;
char *ptr;
/* 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());
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 = (char *)_umalloc(myheap, 100000);
free(ptr);
_uclose(myheap);
if (0 != _udestroy(myheap, _FORCE)) {
puts("_udestroy failed.");
exit(EXIT_FAILURE);
}
if (FALSE == VirtualFree(initial_block, 0, MEM_RELEASE)) {
printf("VirtualFree error: %d.\n", GetLastError());
exit(EXIT_FAILURE);
}
return 0;
}