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<Node*> 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();
}
The problem is, when I check the memory after running the method highestTreePossible(), there's a lot of memory allocated, which isn't supposed to happen, because I deleted everything. Why is my code leaking memory?