I'm fairly new to C++ and I'm trying to implement a tree structure but I'm stuck with a segmentation fault which appears when the tree is deleted. The piece of code is pretty simple, I have a class Node, which contain pointers to its children.
#include <vector>
class Node
{
public:
int data1, data2;
std::vector<Node*> children;
Node* add_child(double data1, double data2)
{
Node* n = new Node(data1, data2);
children.push_back(n);
return n;
}
Node(double data1, double data2)
:data1(data1), data2(data2)
{ }
~Node()
{
for(auto child : children)
{
delete child;
}
children.clear();
}
};
int main()
{
Node root = Node(0, 0);
Node* n = &root;
for(int i = 0; i < NB; ++i)
{
n = n->add_child(0, 0);
}
}
The main create a very simple structure, but it is sufficient to have the error. The seg fault only happened for value of NB greater than 170 000.