65.9K
CodeProject is changing. Read more.
Home

A little "garbage collector" for your project

starIconstarIconstarIconemptyStarIconemptyStarIcon

3.00/5 (4 votes)

Jul 26, 2010

CPOL
viewsIcon

11734

A little class to help you avoid memory leaks

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:

	/*Add new pointer into GarbageCollector's array.
	  Param: memory pointer
	  Returns: memory pointer (param) ***
	  REMEMBER TO AVOID USING DELETE FUNCTION INTO YOUR FUNCTIONS, IF YOU USE THIS GARBAGE COLLECTOR ****/
	void* addNewPointer(void * ptr);

	/*Delete all pointers allocated, and erase all object's allocated pointers.*/
	void freePointers();

	/*Set to true if you've allocated an array into heap (new void [20])
	  Set to false if you've allocated a simple variable into heap (new void)*/
	void setCollectorType(bool type) { collectortype = type;}

	CGarbageCollector(){collectortype = true;}
	/*Will call freePointers() function*/
	~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(); //You can also use the destructor
}