I am using blinky demo example as template and running with qemu(with heap4) and when I try to use srand() and rand() in my program it is using malloc() which halts my programs with following message
Unexpected call to malloc() - should be usine pvPortMalloc() in main.c
When checking the map file, srand() points to a library from arm-none-eabi-gcc.
5036 .text.srand 0x00003fb8 0x5c /Applications/ArmGNUToolchain/12.3.rel1/arm-none-eabi/bin/…/lib/gcc/arm-none-eabi/12.3.1/…/…/…/…/arm-none-eabi/l ib/thumb/v7-m/nofp/libg_nano.a(libc_a-rand.o)
Is this the right srand() function? If not how to include the right srand implementation for freertos
FreeRTOS doesn’t have anything to do with srand and family, that needs to be supplied by the library.
FreeRTOS itself, as supplied here, doesn’t print that message, but seems to be something added by your environment that must be partially supporting FreeRTOS. Normaly, the correct answer is to make sure your implementation (since it seems to be using newlib-nano by the library names) uses and has the interfaces to support the multi-threading system you are using (in the case FreeRTOS).
One thing to check is if the library is providing and using a (weak) version of __malloc_lock and __malloc_unlock, and if so provide an inplementation of those for FreeRTOS. The fact they seem to have put in the error message makes me wonder why they did that and not provide the actually support for FreeRTOS.
See if you have
int rand_r (unsigned *__seed);
That lets you explicitly manage the storage for the state.
Some demos implement a local copy of malloc() that does nothing but assert() to warn users if it ever gets called unexpectedly. Looks like it worked.
Another thing to consider is GNU linker
--wrap option to map malloc to pvPortMalloc - Using LD, the GNU linker - Options.
As stated by @rtel there is a local malloc() handler (instead of a weak function), after using the local malloc in main.c as a wrapper to pvPortMalloc I am able to use srand().
void *malloc( size_t size )
( void ) size;