Memory leak??

Started by
5 comments, last by iMalc 15 years, 7 months ago
I made this class, something like:

class ABC:
{
ABC();
~ABC();
int *a;
int *b;
};


ABC::ABC():a(NULL),b(NULL)
{
a=new int;
b=new int;
}


ABC::~ABC()
{
delete a;
delete b;
}

Later on my code, I will create lots of instances of ABC with operator new, and save then in a STL queue.


queue<ABC*> free_abc_pool;
...
void CreateABC(unsigned int number)
{
 for(unsigned int i=0; i<number;i++)
  {
   ABC* obj=new ABC;
   free_abc_pool.push(obj);
   }
}


I've created a function to delete all of then to:


void DestroyABC()
{

 int size=free_abc_pool.size();

  for(int i=0;i<size;i++)
   {
    ABC* obj= free_abc_pool.front();
    delete obj;
    free_abc_pool.pop();
   }

}


While doing some tests, I realized something; DestroyABC don't free memory as it should!!! If I create 100 ABC objects, task manager says something like 4kb of memory had been allocated. When I call DestroyABC, something like 20 bytes are freed. If I instantiate 10000 ibjects, task manager says something like 16kb of memory allocated, but, again, DestroyABC freed something like 20 bytes only. What is going on?? Oh, I've made testes with 1000 objects to with similar results.
Advertisement
You delete the object at the front, but then pop will remove the last one. I'm surprised your code doesn't crash.
Quote:
Removes the next element in the queue, effectively reducing its size by one. The element removed is the "oldest" element in the queue whose value can be retrieved by calling member queue::front.


From here: http://www.cplusplus.com/reference/stl/queue/pop.html
Sorry, I forgot you were using a queue. Mentally, I switched back to a vector<>.
delete doesn't necessarily release the memory back to the OS. You are measuring how much memory the process has, and that's not a good way to detect memory leaks.

EDIT: Why are you using all those pointers anyway? You can have a queue<ABC> instead of queue<ABC*>, and you can have ABC::a and ABC::b be ints, instead of pointers to int. Memory leaks should not be much of an issue if you use the STL in a natural way.
If you have pointers as members, you have to write your own copy constructor and assignment operator.

ABC::ABC(const ABC& other) : a(new int(other.a)), b(new int(other.b)) { }ABC& ABC::operator = (const ABC& other) {  *a = other->a;  *b = other->b;  return *this;}


The default assignment operator makes a = other.a and b = other.b, and then the destructor of the assigned class deletes the same pointers as the former ones.
Nyarlath is correct. To be more specific, you must follow the rule of three.
"In order to understand recursion, you must first understand recursion."
My website dedicated to sorting algorithms

This topic is closed to new replies.

Advertisement