Everyone knows that it’s easier to prevent a catastrophe than to clean up after one. As embedded software engineers, we know that better than most. According to the Common Weaknesses Enumeration, embedded engineers face three principal catastrophes:
- Integer overflow or wraparound,
- Array and pointer bounds checking, and
- Dynamic memory allocation problems
The great static analysis tools and compilers that are available today cover the first two nicely. At run-time, liberal use of ASSERT and its ilk can assist with the dynamic aspects of the second species of catastrophe. The point of this discussion is catastrophe #3, having to deal with dynamic memory allocation, and therefore the “heap.”
Unlike the GOTO statement, dynamic memory allocation can hardly be considered harmful, but in embedded applications, it might be considered pointless. Every engineering decision is the result of a cost-benefit analysis. In most embedded applications, memory is neither plentiful nor asynchronously freed, so the cost of dynamic memory allocation must be considered to be very high. Where is the overmatching benefit?
Over the years, we have seen many examples of memory leaks, double allocations and use of “deleted” memory. These sorts of problems are very painful to debug, and very easy to fix only partially – condemning developers to debug them all over again. There are also manifold difficulties engendered by what happens when there is no more memory to allocate. In fact, we’ve seen many instances where it is not apparent that developers understand that malloc() can fail. When it does, the only saving grace is that overwriting what exists at address 0 often results in sudden, painful death. In many analyses, this is preferable to lingering malfunction.
Don’t fall for the seeming ease and expandability of “dynamic memory allocation” in embedded systems. Do the hard work. Define the performance envelope of your application. Figure out, beforehand, how to fail gracefully – degrading performance along the way if necessary. If you invite catastrophe, it will come.
Microchip Technology acquires Atmel