Is it good to use dynamic memory allocation in embedded programming?

Before starting I have to mention few references which were really usefull resources in my “Embedded tips and tricks” – related posts. One of them is Dan Saks’ articles and columns on and another one is Netrino web site and Michael Barrs’ articles.

I thought of writing this post in order to explain possible benefits but also the drawbacks that are induced by dynamic memory allocation… in embedded programming. I excluded any faulty use of dynamic allocation such as memory leaks or dangling pointers, so my assumption is that data is correctly allocated and de-allocated.

First of all let me just integrate dynamic allocation in the general storage types classification, there are three types (at least in C):

    Static storage – variables which exist during the whole program execution time; those are global variables and those variables explicitly declared as static

    Automatic storage
    – variables which are allocated upon entrance into a block (something delimited by curly brackets {}) and de-allocated after existing that block (this is the case of local variables)

    Dynamic storage
    – this one falls entirely on users’ responsibility; he manually creates the variables (via malloc, calloc or, in C++ new operator) and he also destroys them (via free or delete)

Dynamic allocation has the advantage of being completely in control of the programmer. Variables storage and lifetime is manipulated solely by the user and it is not necessary to overload the compiler with such task (actually dynamic allocation is done at run-time, so has nothing to do with compiler), but on the other hand he has to be aware that this “freedom” can provoke serious errors.

In embedded programming dynamic memory allocation should not be avoided at all, this is not a good practice, but instead it has to be used carefully.

Read more of this post