In my custom stack allocator, I allocate a large amount of memory at when the program launches using malloc(), then at program shutdown I free() all the memory allocated.
So basically it looks like this:
//start up
m_pInitialPosition = malloc(STACK_SIZE);
//shutdown
free(m_pInitilaPosition);
When I need to create a new object I call allocateNew():
Actor* pActor = getStackAllocator().allocateNew<Actor>();
*pActor = Actor();
This is what allocateNew() looks like:
template <class T>
T* allocateNew()
{
//allocate returns void*
return new (allocate(sizeof(T), __alignof(T))) T;
}
The problem occurs (_BLOCK_TYPE_IS_VALID(pHead->nBlockUse exception) if I call:
delete pActor;
If I simply remove that line the problem disappears and there are no memory leaks because the I still call free() in the stack allocator, but the destructor of Actor is not called…
So what can I change to ensure that the destructor is called?
When you call
delete, the object pointed bypActorwill be destructed and the memory will be freed using the default deallocator (could be free()), not yours. Since the object has been allocated by your allocator, it cannot work.Define a new method to handle object deletion like this one :
And replace your delete by :
This article explains how to make a custom memory allocator : http://bitsquid.blogspot.fr/2010/09/custom-memory-allocation-in-c.html
Moreover, I have a doubt about your code. What are these lines supposed to do ?
1- If allocateNew() performs both allocation & default construction, it is ok but the second line is useless ?
2- If allocateNew() only performs allocation without initializing the object, the second line is wrong : it calls the assignment operator on an uninitialized object.