To access a heap that was not created by the current process, you need to call _uopen. (If you have called _ucreate in the current process, in order to create a heap, this is not necessary; _ucreate automatically opens the heap.)
_uopen(fixedHeap);
This call opens the heap for that particular process; if the heap is shared, each process that uses the heap needs its own call to _uopen.
You can then allocate and free memory from your own heap just as you would from the default heap. To allocate memory, use _ucalloc or _umalloc. These functions work just like calloc and malloc, except you specify the heap to use as well as the size of block that you want. For example, the following code fragment allocates 1000 bytes from fixedHeap:
void *up; up = _umalloc(fixedHeap, 1000);
To reallocate and free memory, use the regular realloc and free functions. Both of these functions always check what heap the memory came from, so you do not need to specify the heap to use. For example, in the following code fragment the realloc and free calls look exactly the same for both the default heap and your heap.
void *p, *up; p = malloc(1000); /* allocate 1000 bytes from default heap */ up = _umalloc(fixedHeap, 1000); /* allocate 1000 from fixedHeap */ realloc(p, 2000); /* reallocate from default heap */ realloc(up, 100); /* reallocate from fixedHeap */ free(p); /* free memory back to default heap */ free(up); /* free memory back to fixedHeap */
For any object, you can find out what heap it was allocated from by calling _mheap. You can also get information about the heap itself by calling _ustats.
When you call any heap function, make sure the heap you specify is valid. If the heap is not valid, the behavior of the heap functions is undefined.
Destroy A Heap
When you have finished using a
user-defined heap, close it with _uclose. Once you have closed the heap in a process, that
process can no longer allocate from or return memory to that
heap. If other processes share the heap, they can still use it
until you close it in each of them. Performing operations on a
heap after you have closed it causes undefined behavior.
To finally destroy the heap, call _udestroy. If blocks of memory are still allocated somewhere, you can force their destruction. Destroying a heap removes it entirely even if it was shared by other processes. Again, performing operations on a heap after you have destroyed it causes undefined behavior.
After you destroy your fixed-size heap, it is up to you to return the memory for the heap (the initial block of memory you supplied to _ucreate and any other blocks added by _uaddmem) to the system.
![]()
Managing
Memory with Multiple Heaps
Advantages
of Using Multiple Heaps
