I have a class with a list of pointers to objects of that same class as an attribute (Children). The problem I have is that when I create an object of that class, add children to it and then try to delete it, it doesn’t really free the memory (judging by the System Monitor). I’m using Ubuntu with g++.
The next code illustrates well my problem. It creates an object, adds ten million children to it and then deletes it. The memory usage goes up from 1.1 to 1.7 gb as I execute the program and It gets stuck there even after the object gets deleted.
¿Does anyone have any idea of what’s happening?
Thanks a lot.
class UDVertex
{
public:
int ID;
list<UDVertex *> Children;
};
void GetChildren(UDVertex * rootVT);
int main()
{
UDVertex * MyVertex;
MyVertex = new UDVertex;
MyVertex -> ID = 0;
GetChildren(MyVertex);
while( ! MyVertex -> Children . empty() )
{
delete MyVertex -> Children . front();
MyVertex -> Children . pop_front();
}
delete MyVertex;
std::cout << "Press enter to continue...";
std::cin.get();
return 0;
}
void GetChildren(UDVertex * rootVT)
{
UDVertex * Child;
int i;
for (i = 0; i < 10000000; i++)
{
Child = new UDVertex;
Child -> ID = i + 1;
rootVT -> Children . push_back ( Child ) ;
}
}
The problem is your method of measuring the memory.
The “System Monitor” moniters memory allocated to a processes (which is done in huge chunks).
Within the processes memory is allocated/reclaimed (after new/delete) by the runtime library; which tracks created and deleted of objects (which are usually tiny in comparison to the pages allocated to the processes). The “System Monitor” does not let you know how much of the memory is currently being actively used by the application (your part of the app) and how much the runtime is holding onto.
A simple test would be to try allocating the objects again (allocate all memory (check-size) release all memory (check-size) allocate all memory (check-size)).
If the memory usage stays about the same size (at each check-size) you know that the deleted objects were given back to the runtime and have now been re-acquired by the application without the processes having to ask the OS for another huge chunk.