In my C++ code, I allocate a huge amount of memory to create a tree, and then I use 'delete' in every node to free the memory.
After I delete everything, I check the amount of used memory by the OS, and I see that the memory wasn't freed. That's expected, because the process doesn't return the memory to the OS right away, because it still might use it again.
The problem is that I create another huge tree right after I delete the first one, and instead of using the already allocated memory, the process allocates more memory from the OS. Because of this, I ran out of RAM and my computer got really slow, to the point where I couldn't even switch tabs. I checked the memory usage at several moments to see if that's what really happened, and it is.
If only I could make the process use the same memory it used before, or maybe if I could force the process to give the memory back to the OS.
What can I do to solve this problem?
(I'm using Debian)
I'm creating a tree of dynamic objects. The Node class has a vector to store the child nodes, among the other class variables:
std::vector child; The class destructor deletes all the dynamically allocated class variables, and then deletes the child nodes:
~Node() {
//Deleting the other variables
.
.
.
//Deleting the child nodes
for(int i = 0; i < child.size(); i++) {
delete child[i];
}
}
My class has a method that creates a tree of a given height, in which the current node is the root node:
void createTree(int height) {
if(height == 0) {
return;
}
for(int i = 0; i < numberOfChildNodes; i++) {
child.push_back(new Node());
child[i]->createTree(height - 1);
}
}
This class has another method where I create a tree with height = 3, then I delete the entire tree and create another one with height = 4, then I delete the entire tree and create one with height = 5, and so on, until a memory limit is reached:
void highestTreePossible() {
int i, height = 3;
struct sysinfo memInfo;
while(true) {
createTree(height);
sysinfo (&memInfo);
if(memInfo.freeram > limit) {
std::cout << "Highest tree possible: height = " << height;
break;
}
for(i = 0; i < child.size(); i++) {
delete child[i];
}
child.clear();
height++;
}
for(i = 0; i < child.size(); i++) {
delete child[i];
}
child.clear();
}