This question pertains to programming on embedded systems. I'm working on an experimental communication stack on an embedded device. The stack receives stream data from the underlying channel, detects discrete packets, reassembles fragmented data, etc...
Each function is implemented in a separate layer. Some layers delay processing of packets (because data arrived in an interrupt handler and further processing is offloaded onto the main context). Some layers merge multiple incoming packets into a single packet forwarded to the next upper layer (i.e. reassembly of fragmented data). Accordingly, some layers split one incoming packet into multiple packets forwarded to the next lower layer. Of course, any layer may at any point drop a packet without further notice because, for example, a checksum didn't match the data.
My question is about memory allocation for these data packets.
Currently, I'm using malloc on each layer. Specifically, I allocate memory for the packet to be forwarded to the next upper layer, pass the pointer to the handler of the next layer and free the memory again after the call. It is the next layer's handler's responsibility to copy the required data. Thus, each layer maintains ownership of the data is allocated and it is hard to forget to free allocated memory. This works very well but leads to a lot of unnecessary copies.
Alternatively, I could forward ownership of the buffer to the next layer. Then the next layer can do its work directly on the buffer and forward the same buffer to the next layer, and so on. I suppose this is somewhat trickier to get right that no memory is leaked.
Ultimately, because it is an embedded device, I want to find a solution without dynamic memory allocation. If each layer keeps ownership of its own memory then implementation without malloc should be easy enough. But if ownership is passed on then it seems more complicated.
Do you have any input?