Search code examples
c++memory-managementnew-operatordelete-operatorarduino-c++

How to prevent memory gaps in C++ new/delete?


This question is based on https://arduino.stackexchange.com/questions/81857/what-would-be-the-best-way-of-dynamically-change-instances-regarding-dynamic-m

I have a base class, and (possibly) many derived classes from it. I want to have 4 instances to those derived classes, but those instances change. E.g. assume derived classes C1..C20, then one instance to C4 is deleted, and a new instance C7 is created.

Due to memory limitations, I cannot create 4 instances of all derived class.

I work on an Arduino platform. Can I assume:

  1. When I delete an instance and new an instance, and the derived classes do not have any instance variables, the memory gap by delete the first instance, will be filled with the instance created by new? Note that the derived classes have different methods (but I think this only affects the V-table).
  2. Can I assume, this also is true when the amount of memory used by an instance is the same? (e.g. if the base class uses 10 bytes, and a derived instance 20 bytes, and the new instance 20 bytes too, it will use the same space?

In case 2 is true, what would be the best way to keep both instances the same (memory) size? Like placing an unused byte array for the difference, e.g.:

class C
{ 
   byte a;
}

class C1: C
{
   byte a;
   long b;
}

class C2: C
{
   byte a;
   byte _unused[4];
}

Guess I also have to keep alignment into account?


Solution

  • You have to make sure that

    • You have enough memory to hold 4 instances of any derived types.
    • The memory alignment is suitable for all derived types.

    Then you can allocate memory enough to hold 4 instances and use new(buffer) Type to construct the instances. Once you're done and want to switch the types, you call the destructor on each instance and use placement new for some other type.