5.4.7 Dynamic Memory Allocation

Dynamic memory allocation is a means for programs to manually request and release arbitrary-sized blocks of memory during program execution. It is available in some form for most devices supported by MPLAB XC compilers.

Programs can call the malloc() or calloc() library functions to allocate blocks of memory at runtime. The requested size does not need to be a constant expression, unlike with static or automatic allocation of objects (with the exception of variable-length automatic arrays, where supported). The contiguous region of memory spanning all the allocated memory blocks is collectively referred to as the heap.

An allocated block of memory that is no longer required can be released, or freed, by the program using the free() library function. Memory that has been freed can potentially be re-allocated at a later time. Failing to free memory no longer required can result in excessive memory use that could prevent the allocation of additional memory from the heap. If the size of an already allocated memory block needs to be changed, the realloc() function can be used.

Depending on your selected target device and options, MPLAB XC compilers may implement a full and/or simplified dynamic memory allocation scheme, or dynamic memory allocation may not be permitted at all. The exact operation of dynamic memory allocation with this compiler is described in the following section. The syntax and usage of the dynamic memory allocation functions is described in the Microchip Unified Standard Library Reference Guide.