richard_damon wrote on Wednesday, August 09, 2017:
Malloc starts off non-thread safe, as it uses some internal state to keep the state of the heap. The simplest solution if you need dynamic allocations and deallocations is to just use a higher number heap version that supports what you need and use that yourself. The only issue is if you use any library functions that call malloc itself, then you need to do something more complicated.
The next step up is to define your own malloc/free that call pvPortMalloc / vPortFree to be thread safe, which works as long as nobody is calling the other heap functions, particularly realloc(), since FreeRTOS doesn’t have a threadsafe version of these.
Another step would be to wrap all cals to any function that might use the heap with some from of protection (like stoping and starting the scheduler), but this is the risk that you might miss one (which would lead to possible heap corruption if two threads are in the heap functions at once),
Some libraries, if they were anticipating being used in a multi-thread enviroment will have a call back function to allow you to make the library thread-safe. (they can’t provide it themselves, as they don’t know what os you are using). One common example is newlib/newlib-nano which is somewhat common, can be configured to have such a call back. If the standard library you are using has such a feature, defining that call back is the best solution.