Search code examples
c++memory-managementpool

How to dynamically allocate an instance of a class in a global char array in C++?


I have this code:

const int size = 1024;
char pool[size];
int nextFree = 0;

class A
{
    ...
}

I have to extend the functionalities of class A in such a way that when a client call a dynamical allocation of this class:

A* a = new A();

then the instance to be placed in the global array pool.

I am thinking of overloading operator new and inside using placement new. Something like this:

class A
{
    ...
    void* operator new(size_t size)
    {
        void * pInt = ::new (&pool[nextFree]) A();
        nextFree += size;
        return pInt;
    }
    ...
}

and it works until it comes to freeing the dynamic allocation where the compiler throws an error: "free(): invalid pointer". I tried overloading operator delete too but with no success.

Any ideas how it should be done the right way?


Solution

  • placement new doesn't allocate memory it just calls the constructor on already allocated memory so delete doesn't make sens. you are just suppose to call the destructor using T::~T() when the object is getting destroyed and deallocate memory(if needed) later.