I am trying to implement a n-ary tree for a project. The structure of the node is as follows, I specifically need to have the link to both the parent node and the children nodes of the said node for my requirements.
struct treeNode {
struct treeNode* parentNode;
std::list<struct treeNode*> childNode;
};
I am using a insertNode()
function to create a node, which is a child node to a particular node which is passed through the argument. The implementation of the said function is as follows -
struct treeNode* treeImplement::insertNode(struct treeNode *pNode) {
struct treeNode* node = (struct treeNode*) malloc(sizeof(struct treeNode));
node->parentNode = pNode;
//std::cout << pNode->childNode.size() << std::endl;
pNode->childNode.push_back(node);
return node;
}
The root node is created at the time of object initialization through class constructor treeImplement()
.
Now I am trying to test my code in the int main()
by calling the insertNode()
function. Here getCurrentNode()
and setCurrentNode()
are to read and write to a currentNode
variable which keeps track of which node we are currently on.
treeImplement ti;
std::cout << ti.getCurrentNode() << std::endl; // to check root node is succesfully created
struct treeNode* t = ti.insertNode(ti.getCurrentNode());
ti.setCurrentNode(t);
std::cout << ti.getCurrentNode() << std::endl;
Running it gives a SIGSEGV error when I am trying to call the insertNode()
. Debugging by commenting and un-commenting the implementation of the insert function, made me found that a specific line within the insertNode()
is creating the issue.
pNode->childNode.push_back(node);
The function runs fine when I do something else(like assigning the child node pointer to a variable) instead of doing a std::push_back()
to the list inside the struct through the pointer.
Now I found the solution to my problem in this previously asked question - segmentation-fault-when-accessing-a-list-inside-a-struct. But I still have some questions and need clarity.
Basically the answers in the above link, suggest using new
instead of malloc()
as the malloc doesn't run any constructor(lack of which apparently causes the problem).
My main question is why do we need a constructor here? What precise function does the said constructor carries out, which is lacking when I am using the malloc?
A particular answer in the above link said that the subobjects inside the struct are unitialised. I am unable to understand to what does that exactly mean? Calling a pNode->childNode.size()
before doing any push backs gives a 0, which means that it is not as if some garbage value is within the list already.