next up previous contents
Next: Standard C/C++ Memory Management Up: Reference of Dynamic Memory Previous: Reference of Dynamic Memory

Creating Heaps

# include  <ucr/heap.h>

struct HEAP_SPACE;

extern HEAP_SPACE* heap_init(void*space, size_t size);
extern void*heap_alloc(size_t size, HEAP_SPACE*space);
extern void heap_free(void*memory);

extern void heap_self_test(HEAP_SPACE*space);

Memory can be divided into heaps from which useful portions are allocated. The application may arrange for segments of memory to be converted into heaps with the heap_init function. Pass to this function a pointer to the start of the segment of memory, and the size of the memory, and heap_init will write into it necessary data structures and return a HEAP_SPACE cookie. heap_init only manipulates the memory within the space, so it is thread-safe.

For example, to create heaps from some architecturally defined segments of memory, use heap_init like so:

HEAP_SPACE*sram_segment = heap_init(SRAM_START, SRAM_SIZE);
HEAP_SPACE*fast_dram = heap_init(DRAM_START, DRAM_END-DRAM_START);

The HEAP_SPACE cookie is a pointer to an opaque type that the application uses to refer to a particular heap, in particular when allocating memory.

The heap_alloc function returns a pointer to memory pulled from the requested heap. For example, heap_alloc(16,fast_dram) returns a pointer to 16 bytes from the fast_dram heap. Besides the extra paramter to identify the heap from which memory is to come, this function behaves just like malloc.

The heap_free function releases memory back to the heap from whence it came. Notice that there is no HEAP_SPACE parameter required. When a segment of memory is allocated, a header is created in front of it that identifies the heap it came from. The heap_free function knows to look for this information and return the memory to the correct heap.


 
Figure 2: Basic Heap Allocation
\begin{figure}
\begin{center}
\begin{verbatim}
 ...

The example if Figure illustrates a few of the basics of using heaps. Note that uCR does not include a special function for destroying heaps. Generally, heaps are permanent (segments of physical memory don't typically vanish) but as the above example shows, it may be perfectly reasonable to dynamically allocate a temporary heap. When pointers no longer refer to memory within the heap, you can destroy the heap simply by releasing the memory for the heap itself.


next up previous contents
Next: Standard C/C++ Memory Management Up: Reference of Dynamic Memory Previous: Reference of Dynamic Memory
Stephen Williams
9/2/1997