Electronic – Dynamically allocating memory for an embedded application

cembeddedmemorymicrocontroller

I am working on a Project that will requires using an MCU to receive frame packets with unknown frame length on reception, but each reception has an octet from which you can deduce the number of frames left to receive and hence calculate the length of the entire frame.

In other to avoid allocating a fixed memory for the receiving frame which might not be used up (if the receive frame length is less that the Max frame length to receive), I am of the opinion to dynamically allocate a memory for the remaining frame to be received.

For example. If we assume a packets of 20 octets and the 3rd octets tells you the number of the remaining octets left to be received (which could be 2, 3, even 17 octets max). Rather than creating a register of size 17, which might not be used up, how can I dynamically allocate this memory especially for an embedded application, so that if the 3rd octets revels that there are 6 octets to be receive, then I simply allocate a register with size 6 for the rest of the frame, with out using the "malloc".

Programming language is C.

I hope my question is clear enough. Please share your views as I need to best possible approach on this.

Thanks.

Best Answer

In this case I would say the best approach is probably just to allocate the maximum memory size, and reuse it for as many other things as possible too.
Some compilers have an option for variables to share memory space providing they are not active at the same time. For example, the (now replaced by HI-Tech C) PIC18 C compiler has an overlay attribute that can be used with variables to do this.
It can also handle variable size arrays which would be perfect for what you wish to do (less overhead than malloc) I would check if your compiler can do this.