0

I am trying to make a insert function to insert string in trie tree. I am using this to convert the non-deterministic grammar to deterministic grammar using left factorization method .In each node I have map. Somewhere I am getting segmentation fault.First time using map so can't figure it out. Thanks in advance.

struct trie_node
{
map<char,trie_node*> char_list;
bool end_of_word;
};

trie_node* init(){

trie_node *root = (trie_node*)malloc(sizeof(trie_node));
root->end_of_word=true;
return root;

}

trie_node* new_node(){

trie_node *temp = (trie_node*)malloc(sizeof(trie_node));
temp->end_of_word = true;
return temp;

}

void insert_in_trie(trie_node *root,string s){
int n = s.length();
    cout<<"bkjb";

trie_node *current = root;
for(int i=0;i<n;i++){
    map<char,trie_node*>::iterator it = current->char_list.begin();
    it = current->char_list.find(s[i]);
    if(it!=current->char_list.end()){
        current = it->second;
    }
    else{

        cout<<"khjkk";
        //make end_of_word false
        current->end_of_word = false;
        pair<char,trie_node*> x;
        x.first = s[i];
        x.second = new_node();
        current->char_list.insert(x);
        //update current
        current = x.second;

    }
}
}

void print_trie(){
cout<<"\n function print_trie"<<endl;
}

int main(){
string s[4] = {"aBcD","aBcDSe","aBcDFz","part"};
int n = sizeof(s)/sizeof(string);
//cout<<n<<endl;

trie_node *root = init();

insert_in_trie(root,"aBcDFz");

//printing trie tree 
print_trie();
return 0;


}
Mahesh Nagarwal
  • 55
  • 1
  • 1
  • 6
  • 5
    `malloc(sizeof(trie_node))` is a major problem. The `malloc` function allocates memory, and that is it. It will not construct objects or initialize them in any way. If you need pointers, first and foremost use [smart pointers](http://en.cppreference.com/w/cpp/memory#Smart_pointers), and if not then use `new` to allocate memory *and construct objects*. – Some programmer dude Feb 01 '18 at 17:08
  • @Someprogrammerdude That's an answer. – Ron Feb 01 '18 at 17:14
  • @Ron If that is *the* problem then yes, but I don't know that, only that is is *a* problem. – Some programmer dude Feb 01 '18 at 17:18
  • 3
    I have to ask this -- what book, teacher, or website shows you to use `malloc` in a C++ program? Even poor C++ books do not show this, so is this something you came up with on your own? I answered a question just yesterday that had the exact same issue [here](https://stackoverflow.com/questions/48544217/program-received-signal-sigsegv-segmentation-fault-c-list/48545252#48545252) – PaulMcKenzie Feb 01 '18 at 17:27
  • Not related to the crash, but `x` in `insert_in_trie` should be `pair x;`. Or better yet, just use `current->char_list.emplace(s[i], new_node());` and get rid of `x` completely. – 1201ProgramAlarm Feb 01 '18 at 17:35

0 Answers0