title: How to dynamically allocate an instance of a class in a global char array in C++?
body: <p>I have this code:</p>
  
  <pre><code>const int size = 1024;
  char pool[size];
  int nextFree = 0;
  
  class A
  {
      ...
  }
  </code></pre>
  
  <p>I have to extend the functionalities of <code>class A</code> in such a way that when a client call a dynamical allocation of this class:</p>
  
  <pre><code>A* a = new A();
  </code></pre>
  
  <p>then the instance to be placed in the global array <code>pool</code>.</p>
  
  <p>I am thinking of overloading <code>operator new</code> and inside using <code>placement new</code>. Something like this:</p>
  
  <pre><code>class A
  {
      ...
      void* operator new(size_t size)
      {
          void * pInt = ::new (&amp;pool[nextFree]) A();
          nextFree += size;
          return pInt;
      }
      ...
  }
  </code></pre>
  
  <p>and it works until it comes to freeing the dynamic allocation where the compiler throws an error: "free(): invalid pointer". I tried overloading <code>operator delete</code> too but with no success.</p>
  
  <p>Any ideas how it should be done the right way?</p>