Slashdot Mirror


Dynamic Memory Allocation in Embedded Apps?

shootTheMessenger asks: "My company is porting our C++ Windows app to C in an embedded device and the question of whether to use dynamic memory allocation continues to come up. So far I have resisted malloc/free use but it gets tedious having the same argument with the next set of managers to take an interest in the project. Is there a definitive answer on the subject, especially one to counter the 'we have plenty of RAM - 16MB - so why not use dynamic allocation' argument? A quick google search finds that some sites frown on allocations within embedded applications, while others say it is OK in some contexts and yet others hack around it with pseudo-static allocations. How do you feel about this particular subject?"

2 of 102 comments (clear)

  1. Why? by ObsessiveMathsFreak · · Score: 2, Interesting

    My company is porting our C++ Windows app to C in an embedded device and the question of whether to use dynamic memory allocation continues to come up.

    OK, I realise I know precious little about embedded devices, but exactly why do you even need to port the code from C++ to C. Surely there's a C++ compiler for the device, but if there isn't, naturally I see the issue.

    Secondly, dynamic memory in an embedded device?! Something seems awry here. Would preallocating memory work just as well? You, in theory, know all the parameters and tolerences beforehand.

    Lastly, going back to the first paragraph, I'd keep away from C if I could, especially considering that the C++ system is likely object oriented. On top of that new/delete is much superior to the malloc/free. But that is just my humble C++ centric opinion!

    --
    May the Maths Be with you!
    1. Re:Why? by try_anything · · Score: 3, Interesting
      I second sticking with C++. The poster may have a good reason for switching to C, but he should have explained it, because the difference between C and C++ is extremely relevant to his question! Thanks to RAII and smart pointers like boost::scoped_ptr (see boost.org) C++ is way ahead of C for using dynamic memory allocation safely and readably. Switching to dynamic allocation will likely involve much greater cost in bugs and readability if C is used instead of C++.

      Also, if performance is important, it's important to be able to experiment with allocation methods when you run into problems. In C++, the ability to implement new and delete differently for each class allows you to experiment with custom allocators without rewriting your code, even if you didn't think of it beforehand. If you use C, make sure you wrap your calls to malloc and free in case you need to tinker later!