10.7 Dynamic Memory Allocation
Dynamic memory allocation is the runtime allocation of uninitialized memory for
arbitrary-sized data objects by various standard C library dynamic memory management
functions that are explicitly called by the programmer (such as calloc,
malloc and realloc) along with the C++
new operator. The memory for the objects is allocated from a region
of reserved memory, usually called the heap. Memory allocated in this way can be freed
for reuse by calling additional library routines (such as free) or the
C++ delete operator, although indiscriminate use of this feature can
lead to memory fragmentation.
There are two libc implementations of dynamic memory allocation
available, allowing the programmer to select between a reduced code footprint or better
memory management. These implementations can be selected using the
-mmalloc-variant=scheme option.
Lite allocation uses a simple algorithm for allocating and freeing chunks of memory from
the heap, resulting in a smaller code footprint and almost no runtime overhead. However,
memory can easily fragment when allocating and subsequently freeing memory chunks in
this way. This dynamic memory allocation implementation is selected when using the
-mmalloc-variant=lite option or when this option has not been
specified.
Binned allocation maintains free (unallocated) chunks of memory in bins, grouped by size.
Algorithms are used to search for suitable memory chunks within the bins when requested.
This algorithm adds some runtime overhead but overcomes many of the memory fragmentation
problems associated with other schemes. The binned form of dynamic memory allocation
will be utilized when using the -mmalloc-variant=binned option has been
specified.
--defsym=_min_heap_size linker
command line option. An example of allocating a heap of 512 bytes using the command line
is:xc32-gcc -mprocessor=32MZ2048ECH100foo.c -Wl,--defsym=_min_heap_size=512An
example of allocating a heap of 0xF000 bytes using the xc32-g++ driver
is:xc32-g++ -mprocessor=32MZ2048ECH100vector.cpp -Wl,--defsym=_min_heap_size=0xF000The
linker allocates the heap immediately before the stack.