Hi!

I hope you could help me with this one. I simplified the code of my program to its basic problem, and the problem is that I do not seem to understand why this program does not release its memory. I check it at the moments of the getline 's, using Ubuntu's System Monitor.

I claim 1000 array's of 1000 items, containing int's. That consumes 4M, and that is what the System Monitor indicates. But when I try to free memory, this does not seem to help. Why? Is it because I do not free memory appropriately, or is the used space never claimed back by the operating system?

Thanks in advance for your help!

Bart.

class C
{
public:

   int *bla;
   C()  {bla = new int[1000];}
   ~C() {delete[] bla;}
};

int main(int argc, char *argv[])
{
   string t;
   set<C*>* pSet;
   set<C*>::iterator iter; 

   pSet = new set<C*>;

   getline(cin, t);
   for (int i=0; i<1000; i++)
   {
      pSet->insert(new C());
   }
   getline(cin, t);
   for (iter=pSet->begin(); iter!=pSet->end(); ++iter)
   {
      delete *iter;  
   }
   getline(cin, t);
   pSet->clear();
   getline(cin, t);
   delete pSet;
   getline(cin, t);

   return 0;
}

The memory is freed, it's just not given back to the OS.

This is so you can allocate and free memory through the life of the program without going to the hassle of asking the OS each time you want some more memory.

If you repeat the allocation, then your system monitor should show no change. If it does keep going up with each new allocation, and you think you are freeing memory, then you may have a leak.


When you finally quit the program, then all will be well.

Hi Salem,

thanks for your answer. Indeed, this is the solution in this program. Seems that I have to look through my original program now, and search for the bug... :(

Consider using valgrind (since you're using some kind of Linux) to help you track down the memory leaks.

Though you might want to practice with small programs like your example, with carefully introduced deliberate mistakes to get used to the kind of things it tells you.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.