Dynamic memory management


I need to use an user defined number of elements throughout my program. That means I need to new up new instances of that data structure(s) I'm using. The user can add and remove instance through the UI displayed on a LCD.

So, I need the new and delete operators but also something that will dynamically track a collection or list of object references. First question is of course:

Is there an existing (linked) list or vector or collection class that I could use?

If not so, I should write one myself and should I favor small but fragmented memory allocation using a linked list or should I favor re-allocations of continues memory blocks with a collection (basically a dynamic array)?

If there are any other suggestions you might give concerning dynamic memory management, please...

Thanx, Marc

If you haven't figured it out, there ain't a whole lot of memory to be allocating! And if you could, the chance of tieing up the wrong chunk of memory is way to high. You would be better off using an array so you can control/limit how much memory is used (and even check to see if the stack is encroaching on the variables) Otherwise 1 function call could crash your program.

Use a managed block.

Allocate a chunk of memory as big as the max number of objects. ( no point making it smaller as you said a user has the ability to create max objects. )

If you haven't run out of memory yet, you can now create your objects in that block.

void *v_Data = malloc( sizeof( MYSTRUCT ) * MAX_OBJECTS );

MYSTRUCT *m_Data = ( MYSTRUCT* ) v_Data;

m_Data->MYSTRUCT(); //Construct object.

m_Data++; //Move to next memory block.

m_Data->MYSTRUCT(); //Construct second object

//Do stuff with objects

//When done
m_Data = ( MYSTRUCT* ) v_Data; //Ptr back to start
m_Data->~MYSTRUCT(); //Destruct objects.
m_Data->~MYSTRUCT(); //Destruct objects.

//When done
free( v_Data  );

This way, only the block can become fragmented, not the whole SRAM ( only 1 allocation )

You can use the block of data like an array too.

Yes, that’s a great idea! Thanx.

I probably need multiple blocks for different types and just have to pass pointers around to get the object model I need.

As long as your objects don't overlap, mixing object types in the void* buffer is fine, just remember which type each element is.

The only fall back is you can't use the block as an array as the types are mixed ( really only a problem if the sizes are different, you can work around different types ).