how bad is it to use dynamic datastuctures on an embedded system?

后端 未结 8 1562
深忆病人
深忆病人 2020-12-13 21:38

So 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

相关标签:
8条回答
  • 2020-12-13 22:09

    It depends as the meaning of "embedded" in my view broadened in the last 4 years.

    Traditionally, embedded devices had microcontrollers on them and generally no operating system. No protected memory, and were single threaded. You would have to be extremely careful with malloced memory because it's so easy to run out of it when you've only got 32KB of it available for example. So generally, we'd write our code with fixed sized buffers and never use malloc or at if it was every used - very sparingly.

    In the last few years we are seeing what are essentially single chip pc's or micro boards that are easily as powerful as our old Pentium PC's. RAM prices are so cheap now and so small that the memory limitations are nothing like they were. They also often run embedded linux or wince so now we have the ability to use dynamic memory more liberally.

    With this is the ability to use a much wider range of languages including Java, C++, many scripting languages and other languages that provide buffer overrun protection and exception handing and other higher level languages. So really, those old problems are not like they used to be.

    I suspect all this new available hardware comes a new range of issues.

    0 讨论(0)
  • 2020-12-13 22:10

    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.

    0 讨论(0)
提交回复
热议问题