GarbageCollector freezes
Posted: Mon Jul 30, 2012 2:45 pm
I made a garbage collector for my game to make sure all of the entities get deleted at the end. Whenever you try to delete an entity it freezes. It has its own Alloc and Dealloc functions, and MarkTrash deletes that entity the next time Collect is called by adding it to the trash list.
GarbageCollector:
Collect function:
and this is how it's used:
I have no idea why this won't work. Everything except Dealloc and Collect work (even CleanUp). I didn't show dealloc because its the same as Collect without the trash loop. One thing I do know is that it freezes when it reaches the marked line where it deletes the entity.
GarbageCollector:
Code: Select all
template<class T>
struct Block
{
T* ptr;
unsigned long length;
};
template<class T>
class GarbageCollector
{
protected:
LinkedList<Block<T>> mem;
LinkedList<T*> trash;
public:
GarbageCollector();
~GarbageCollector();
static inline GarbageCollector<T>& Inst() {
static GarbageCollector<T> inst;
return inst;
}
//memory management
T* Alloc();
T* Alloc(unsigned long length);
bool Dealloc(T* ptr);
T* Track(T* ptr,unsigned long length = 1);
//garbage collection
void MarkTrash(T* ptr);
void Collect();
//mem info
unsigned long GetLength(T* ptr);
//clean up remaining memory
void CleanUp();
};
Code: Select all
template<class T>
void GarbageCollector<T>::Collect()
{
Node<T*>* it;
for(it=trash.first;it!=NULL;it=it->next)
{
Node<Block<T>>* bIt;
for(bIt=mem.first;bIt!=NULL;bIt=bIt->next)
{
if(it->data == bIt->data.ptr)
{
unsigned long length = bIt->data.length;
if(length>1){
delete[] bIt->data.ptr;
}
else{
delete bIt->data.ptr; //freezes here
}
mem.DeleteNode(bIt);
break;
}
}
}
trash.ClearList();
}
Code: Select all
GarbageCollector<Entity>& EntityGC = GarbageCollector<Entity>::Inst();
Entity* test = EntityGC.Alloc();
//add components here
while(!quit)
{
//Update
//Render
EntityGC.Collect();
}
//exit