Whether the FreeRTOS support rand()?

When I use the mps2-an385 QEMU model, I used rand() to generate random number. However, when the .out file is running, the terminal shows some error information like this:
Unexpected call to malloc() - should be usine pvPortMalloc()
what can I do to solve this problem? Is there any function in FreeRTOS to replace rand()?

rand is usually part of the C-library coming with your compiler toolchain. It‘s unrelated to FreeRTOS.

But the pvPortMalloc() is a function of heap4.c, I don’t know why when I use rand() the error will occur.

the implementation of rand() you have probably calls malloc().

Try the reentrant version rand_r which is recommended for multitasking applications anyway. Chances are that providing the seed avoids internal malloc (of seed ? Don’t know).
I guess your C-lib is open source. You might check the implementation of rand vs. rand_r in the library source.

I got the answer in another post! The reason of this error is the function in the main.c

void **malloc( size_t size )
{
	( void ) size;
	return pvPortMalloc(size);
	/* * This project uses heap_4 so doesn't set up a heap for use by the C
	library - but something is calling the C library malloc().  See
	https://freertos.org/a00111.html for more information. */
	// printf( "\r\n\r\nUnexpected call to malloc() - should be usine pvPortMalloc()\r\n" );
	// portDISABLE_INTERRUPTS();
	// for( ;; );
}

Change it as the above shown and the rand() will be normal

But it’s still not reentrant. So be careful when using it in multitasking apps or use rand_r appropriately.

1 Like