How long did you debug your application to find a memory leak?
Now, i think that I found a little solution to this problem. Here is it.
CGarbageCollector.cpp
#include "CGarbageCollector.h"
void* CGarbageCollector::addNewPointer(void * ptr)
{
this->_ptrs.push_back(ptr);
return ptr;
}
void CGarbageCollector::freePointers()
{
for(int i=0;i<this->_ptrs.size();i++)
{
if(this->_ptrs[i] != NULL)
{
if(this->collectortype == true)
delete [] this->_ptrs[i];
else
delete this->_ptrs[i];
this->_ptrs[i] = NULL;
}
}
this->_ptrs.clear();
}
CGarbageCollector::~CGarbageCollector()
{
this->freePointers();
}
CGarbageCollector.h
#ifndef CGARBAGE_COLLECTOR_H_
#define CGARBAGE_COLLECTOR_H_
#include <vector>
class CGarbageCollector
{
public:
void* addNewPointer(void * ptr);
void freePointers();
void setCollectorType(bool type) { collectortype = type;}
CGarbageCollector(){collectortype = true;}
~CGarbageCollector();
private:
bool collectortype;
std::vector<void*> _ptrs;
};
#endif
This class is very simple to use.
1) You need to declare an istance of CGarbageCollector class
2) Whenever you allocate a pointer, you must call addNewPointer function.
Important Notes:
- The function returns the same pointer, passed as parameter.
- The function DOESN'T allocate the pointer.
- If you use this class, you must remember to avoid using delete construct.
Example:
[...]
char * myFunc()
{
char * foo = new char [10];
return foo;
}
int main()
{
CGarbageCollector collector;
char * hello = new char [20];
collector.addNewPointer(hello);
char * hi = (char*) collector.addNewPointer(myFunc());
collector.freePointers(); }</br>