Many C runtimes will ship with an implementation of malloc, but the embedded, oriented versions won't necessarily be thread safe by default. Because each C runtime is different, the steps needed to make malloc thread safe will vary. The included STM toolchain used in this book includes newlib-nano as the C runtime library. The following are a few notes regarding newlib-nano:
- newlib-nano uses malloc and realloc for stdio.h functionality (that is, printf).
- realloc is not directly supported by FreeRTOS heap implementations.
- FreeRTOSConfig.h includes the configUSE_NEWLIB_REENTRANT setting to make newlib thread safe, but it needs to be used in conjunction with the appropriate implementations of all stubs. This will allow you to use newlib-based printf, strtok, and so on in a thread-safe manner. This option also makes general use case calls to malloc and free safe to use from anywhere, without you needing to explicitly use pvPortMalloc and vPortFree.
Luckily, there aren't any calls to raw malloc in the example code included in this book. Normally, the STM HAL USB CDC implementation would include a call to malloc, but this was converted to a statically defined variable instead, which enables us to simply use the heap implementations included with FreeRTOS.
Now that we've come to terms with different safety options using dynamic allocation, let's take a look at some additional tools that FreeRTOS has for reporting the health of our stacks and heaps.