Dynamic memory allocation approaches for C++ apps - pros and cons

Joel Sherrill joel.sherrill at oarcorp.com
Mon Dec 3 21:28:31 UTC 2007

Angelo Fraietta wrote:
> Robert S. Grimes wrote:
>> Might I ask what you based your allocator on?  Did you use a chunk of 
>> memory from the heap, and manage that yourself?  Or did you use RTEMS 
>> Regions or Partitions?  I'm particularly interested in the "quality" of 
>> those subsystems.
> I created a linked list for each class and allocated will malloc when i 
> needed it - the size of the required memory is passed in operator new of 
> the class. Instead of freeing the memory when I released in my app via 
> 'delete' , I put it aside and cached for use in the next allocation via 
> 'new'
I was out of town for a family funeral this weekend
so am catching up on this thread.

(1) I often do the same type of thing Angelo describes
even on native programs just to avoid the overhead of
newing/deleting objects.  This also lets me control
calling limits on the number of instances.

(2) Much code is terribly optimistic about malloc() and
doesn't ever worry about it failing.  This can result in
strange situations when you do run out of memory.

(3) RTEMS Design Comments:

+ Partitions are implemented as RTEMS SuperCore Chains
with user data being managed.  If this code doesn'ti
work reliably, then nothing in RTEMS would since Chains
are the foundation of everything.

+ Regions are implemented as RTEMS SuperCore Heaps.
with the added capability to block for memory to become
available.  The C Program Heap and RTEMS Workspace are
also SuperCore Heap instances.  In older RTEMS versions
Malloc was implemented on top of a Region.  In newer
versions, it is implemented directly as a Heap.  So again,
fundamentally the code has to work.

+ The SuperCore Heap uses a first fit allocation algorithm.
I can see where it might be better in some cases to look
farther down the free list for a best fit.  But ultimately,
if you malloc/free enough there will be fragmentation since
we can't change the address of blocks given to the application
so we can't do any movement of memory to make larger
free blocks.

+ There is no garbage collection and no need for garbage

+ Freeing memory in the RTEMS SuperCore Heap is a strictly
constant time operation.  You can merge with the free block
immediately before or after you in memory or with both.  But
that's it.  If using the Region, freeing memory can unblock
multiple tasks.  But free() calls won't because you can't
block on malloc().

This area of RTEMS isn't something to be scared of but it does
have characteristics to be aware of.


More information about the users mailing list