'I am trying to implement a tree with infinite nodes but its giving SEGMENTATION FAULT as an error?
I was making a project where you can search for a ques where I was implementing tree as in the ques asked would be divided into words and questions would be stored in words in form of tree for example
root
/ | \
what where why
/ | | \ \ \
is are is are is are
but its giving me error while trying to access the array inside the structure.
#include <bits/stdc++.h>
using namespace std;
struct node{
string ques;
string ans;
node* child[100];
int noc;
node(string word){
noc=0;
ques=word;
child[0] = NULL;
}
};
node* findnode(node* pnode,string q){
for(int i=0;i<pnode->noc;i++){
if(pnode->child[i]->ques==q){
return pnode->child[i];
}
}
return NULL;
}
node* createnode(node* pnode,string word){
node* childnode= new node(word);
pnode->child[pnode->noc++]=childnode;
return childnode;
}
string ansnode(node* pnode){
return pnode->ans;
}
void storeans(node* pnode,string ans2){
pnode->ans=ans2;
}
int main(){
node* root=new node("root");
node* p= root;
string s[4]={"What","is","your","name"};
for(int i=0;i<4;i++){
p = findnode(p,s[i]);
if(!p){
p=createnode(p,s[i]);
}
}
return 0;
}
I am kind off new to this and was doing this for my project, so pardon if I am doing something silly.
Error is [Done] exited with code=3221225477 in 1.484 seconds
Solution 1:[1]
The logic is wrong here:
p = findnode(p,s[i]);
if(!p){
p=createnode(p,s[i]);
}
findnode returns NULL when it cannot find a child in p with s[i]. You check if it is NULL via if (!p) and then you are calling createnode(p,s[i]) to add a child at p, but p is NULL. Eventually pnode->child[pnode->noc++]=childnode; is undefined behavior because you are dereferencing a nullptr.
If you cannot find the node then you want to add a child at the current node, not at the NULL that findnode returned to indicate that it could not find the child:
auto next = findnode(p,s[i]);
if(!next){
next=createnode(p,s[i]);
}
p = next;
If you had used a debugger you could have seen that p passed to createnode was a nullptr.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | 463035818_is_not_a_number |
