Search code examples
liststackqueueavr

Why shouldn't I use dynamic data structures on an embedded system?


In an embedded systems unit that I'm taking at uni next year, we will learn that dynamic data structures are a bad thing to have in an embedded system program. But the lecture notes don't go into why.

Now I'm working on a moderate scale, embedded systems controller, mostly just takes advantages of the peripheral of the "Butterfly" demo board for the AVR169MEGA. Produced 4 PWM signals to control servo's and ESC. And also to provide a 9-seg LCD screen.

Now I can't think of any better way to store instructions as they are received via USART serial than a queue. Especially for things where I'll need to wait until an unknown amount of data has been received: e.g. a string to display on the LCD screen.

So why don't you use dynamic data structures on a microcontroller in embedded systems? Is it just that you're on a heavily memory restricted environment, and have to be sure your mallocs are succeeding?


Solution

  • There are a number of reasons not to use malloc (or equivalent) in an embedded system.

    • As you mentioned, it is important that you do not suddenly find yourself out of memory.
    • Fragmentation - embedded systems can run for years which can cause a severe waste of memory due to fragmentation.
    • Not really required. Dynamic memory allocation allows you to reuse the same memory to do different things at different times. Embedded systems tend to do the same thing all the time (except at startup).
    • Speed. Dynamic memory allocation is either relatively slow (and gets slower as the memory gets fragmented) or is fairly wasteful (e.g. buddy system).
    • If you are going to use the same dynamic memory for different threads and interrupts then allocation/freeing routines need to perform locking which can cause problems servicing interrupts fast enough.
    • Dynamic memory allocation makes it very difficult to debug, especially with some of the limited/primitive debug tools available on embedded system. If you statically allocate stuff then you know where stuff is all the time which means it is much easier to inspect the state of something.

    Best of all - if you do not dynamically allocate memory then you can't get memory leaks.