title: Am i fragmenting the heap? And how not to or otherwise be better
body: <p>I'm working in C++ for Arduino running on an ESP8266.</p>
  <p>I have a long lived object which maintains two collections of sub-objects (two different types).</p>
  <p>These two collections will have the order of ~5-20 elements each by the end of the long-lived object's life, although the upper bound is not fixed. Realistically it wont be much more than 20 if it ever is, it wont be 100 for example.</p>
  <p>My code for maintaining each collection looks like this (only showing one here for brevity):</p>
  <pre><code>void MyLongLivedObject::addSubObject(SubObject* obj)
  {
      SubObject** newColl = new SubObject*[this-&gt;collectionCount + 1];
      for (uint8_t i = 0; i &lt; this-&gt;collectionCount ; i++)
          newColl[i] = this-&gt;collection[i];
      delete this-&gt;collection;
      this-&gt;collection = newColl;
  
      this-&gt;collection[this-&gt;collectionCount++] = obj;
  }
  </code></pre>
  <p>Is my understanding right that as each of the two collections are expanded by adding objects, they are moved to  the end of the heap memory, leaving a hole? So if i were to alternate adding objects to each collection they would basically walk their way down the heap?
  And then maybe at some point the hole at the start of the heap would be large enough to accommodate one of the collections and it would get moved back there.</p>
  <p>I know the question of &quot;is this a good idea?&quot; is subjective and will depend on many things. To avoid that, can I instead ask for input on how to answer this question myself? What things should I be considering, how do I determine if this is acceptible or not? What questions do I need to answer to be comfortable with this implementation (i.e. to not horribly fragment the heap and cause related woe)?</p>
  <p>Alternatively - if this whole approach is rubbish, what should I be doing instead?</p>