cancel
Showing results for 
Search instead for 
Did you mean: 

Malloc Calloc operations in STM32F4 without RTOS

DJ1
Associate III

Hi, i have an application where i have to read data and store in a buffer, now the buffer length depends on the data_len byte once received from the slave. Than is it wise to use Malloc/Calloc functions? Basically is the dynamic memory allocation supported in case if i am not using RTOS as usually the OS takes care of memory allocation. 

4 REPLIES 4
Pavel A.
Evangelist III

 is it wise to use Malloc/Calloc functions?

Not wise. FreeRTOS has its own allocation method (actually, choice of several methods one of which is malloc/free). But the best for simple embedded systems is either dumb static storage of max. size, or a pool of fixed size blocks. FreeRTOS has also "stream buffers", this can be exactly what you need.

Great i came to know about stream buffers, but the thing is i am not using RTOS for my simple RS232 data read application but here the data length is depending on 1 byte received from the slave device which indicates how much data the packet is holding. Now, if a allocate a big static buffer, i feel it might be waste of memory allocation for me. So is there any way to solving this.

Still, you must be able to process the longest message, so you must have enough memory to store it. It's generally not a good idea to use dynamic allocation in small systems.

My STM32 stuff on github - compact USB device stack and more: https://github.com/gbm-ii/gbmUSBdevice

Depends, dynamic allocation itself is not a problem if the resources are taken and freed. The pitfalls are resource leaks where you cause fragmentation or just consume all the memory over long (infinite) run time. Or mismatched life spans.

You could use pools, and provide a method to flush or purge periodically. 

Personally I'd chase down all leaks, and look for orphans. I've done this in Windows app, it forces a lot of rigor in how you allocate and handle memory resources. Track owners, and limit copies of pointers, have them in a structure or object and force consistent usage even if that means walking a chain each time.

Instrument your code so you can monitor the health of stack and heap against expectations, and hard coded constraints. 

 

Tips, Buy me a coffee, or three.. PayPal Venmo
Up vote any posts that you find helpful, it shows what's working..