### Create Your Own Function to Expand A Heap

When you call _umalloc (or a similar function) for your heap, _umalloc tries to allocate the memory from the initial block you provided to _ucreate. If not enough memory is there, it then calls a getmore_fn function which you have defined. Your getmore_fn function then gets more memory from the operating system and adds it to the heap.

Your getmore_fn function must have the following prototype:

    void *(*getmore_fn)(Heap_t uh, size_t *size, int *clean);

uh is the heap to be expanded.

size is the size of the allocation request passed by _umalloc.

You should return enough memory at a time to satisfy several allocations; otherwise every subsequent allocation has to call your getmore_fn function, reducing execution speed. Make sure that you update the size parameter if you return more than the size requested.

Your function must also set the clean parameter to either _BLOCK_CLEAN, to indicate the memory has been set to 0, or !_BLOCK_CLEAN, to indicate that the memory has not been initialized.

Be sure that your getmore_fn function allocates the right type of memory for the heap:

- Regular or shared memory
- Regular, tiled, or shared memory

The following code fragments show examples of a getmore_fn function:

    static void *getmore_fn(Heap_t uh, size_t *length, int *clean)
    {
    char *newblock;

    /* round the size up to a multiple of 64K */
    *length = (*length / 65536) * 65536 + 65536;

    newblock = VirtualAlloc(NULL,*length, MEM_COMMIT, PAGE_READWRITE);

    *clean = _BLOCK_CLEAN; /* mark the block as "clean" */
    return(newblock); /* return new memory block */
    }

    static void *getmore_fn(Heap_t uh, size_t *length, int *clean)
    {
    char *newblock;

    /* round the size up to a multiple of 64K */
    *length = (*length / 65536) * 65536 + 65536;

    newblock = VirtualAlloc(NULL,*length, MEM_COMMIT, PAGE_READWRITE);

    *clean = _BLOCK_CLEAN; /* mark the block as "clean" */
    return(newblock); /* return new memory block */
    }

With shared memory, you must ensure that all processes have access to the memory being added to the heap.

In the same way as for fixed heaps, you can also use _uaddmem to add blocks to your expandable heap. _uaddmem works exactly the same way in both cases.

Manage Memory with Multiple Heaps

Create an Expandable Heap
Create Your Own Function to Shrink a User-Defined Heap

C Library Functions: Dynamic Memory Management