Dynamic allocation in C and C++

June 30, 2008

Dan_Saks-June 30, 2008

I recently presented arguments for and against using dynamic memory allocation in C and C++ programs.1 I do agree that truly safety-critical systems should avoid using dynamic allocation because the associated risks outweigh the advantages. However, I strongly suspect that many other embedded systems could be improved by judiciously using dynamic memory allocation. In places where the standard C or C++ allocation and deallocation functions are less than ideal, a customized memory manager might work much better.

Ideally, a customized memory manager should look and act like a standard one to the greatest extent possible. Although the customized allocation policy will be different from the policy of a standard one (that's the whole point of using a custom scheme), the parameters and return values of the customized allocation and deallocation functions should be as similar as possible to the standard ones. This similarity lets you build and test your code using standard memory management functions and then slip customized functions in or out as needed with minimal fuss.

Understanding the ins and outs of dynamic memory management is especially worthwhile for C++ programmers. C++ offers many facilities--most notably classes with constructors and destructors--that dramatically diminish the incidence of memory leaks. C++ also lets you define allocation and deallocation functions for each class, making it remarkably easy to insert customized memory managers into existing code. You can even use allocation functions to place objects representing device registers at memory-mapped locations.

This month, I'll contrast the standard allocation and deallocation facilities in C with those in C++. Understanding the differences between these facilities is insightful regardless of which language you use.

The standard C functions
Standard C provides two memory allocation functions, malloc and calloc, and one deallocation function, free. A fourth function, realloc, does both deallocation and allocation. All four functions are declared in the standard header <stdlib.h>.

< Previous
Page 1 of 4
Next >

Loading comments...

Most Commented

  • Currently no items

Parts Search Datasheets.com

KNOWLEDGE CENTER