Search code examples
cmemorycoding-styleembeddedmisra

Popular use of Dynamic memory allocation


I have been reading coding standards in C and most of them discourages use of dynamic memory allocation.But In popular use Dynamic memory allocation leads .Any solid reason for this.I am asking the reasons for its use despite the Demerits it posses ? These are my references JPL Standards :http://lars-lab.jpl.nasa.gov/JPL_Coding_Standard_C.pdf Power of 10 :http://spinroot.com/gerard/pdf/P10.pdf


Solution

  • Dynamic memory allocation is generally banned in embedded systems programming, particularly in safety-critical embedded software. All industry standards for safety-critical software bans it: MISRA-C, DO178B, IEC 61508, ISO 26262 and so on.

    There are many well-known issues with dynamic memory allocation: slow and possibly indeterministic access time, memory leaks and heap fragmentation.

    None of these issues are desired in any kind of program. But in PC/desktop etc programming, they are regarded as a necessary evil, mainly because the mainstream operative systems restrict the amount of static process memory given to each process and if you want to store data beyond that, you have to store it on the heap.

    It is also convenient to use dynamic memory when the amount of data isn't known until runtime. However, there exist no computer in the known world with unlimited memory, so "I want to use a completely variable amount of data, I don't know how much" is kind of a nonsense argument. A proper software engineer always designs for the worst case scenario.

    Particularly in embedded systems, where the amount of RAM is limited and the consequences of bugs are far more dire than an out-of-memory message box popping up, your program must have 100% deterministic behavior. You can't design in things like "this program will work until it runs out of RAM, then it will crash and burn". You can't allow a variable "x" number of trains to exist in your railway supervisory system, you must specify the upper limit and design the system after that.

    So no matter all the issues with dynamic memory mentioned above, you don't want to use dynamic memory in these kind of systems, simply because it doesn't make any sense.

    Recursion is also banned from these systems, for pretty much the same reasons.