Replacing malloc and free

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.
See the Dave Nadler link in the Further reading section for more information and detailed instructions on how to use newlib safely in a FreeRTOS project with the GNU toolchain.

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.

The malloc call in the STM-supplied USB stack was especially sinister because it occurred inside the USB interrupt, which makes it especially difficult to guarantee thread safety during malloc. This is because, for every call to malloc, interrupts would need to be disabled from within the tasks and also within interrupts that made calls to malloc (USB in this case). Rather than go through this trouble, the dynamic allocation was removed altogether.

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.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
13.59.34.87