0

I have used a trie to load my dictionay, and as far as i can tell it loads OK. But when check runs I get Segmentation fault when it checks the trie! I have used GDB and it seems to load OK, only getting new node if needed (ie not for "c a t" in caterpiller) Here are parts of my code:

    // set up trie
    typedef struct node
    {
        bool is_word;
        struct node* children[27];
    }
    node;
    node* root;

    bool check(const char* word)
    {
        node* cursor = root;
    // get word[i]
    // k = word[i] changed to int ( 0 to 26)

    // check letter
        if (cursor -> children[k] == NULL)  THIS IS WHERE GDB "SEGMENTATION FAULT"
        {
            return false;
        }
       // if check for end of word (children[k] -> is_word = true & i is end of word)
            // return true
     // else move cursor move   
    }

    bool load (const char* dictionary)
    {
        node* root = malloc(sizeof(node));
        node* cursor = root;
      // load dictionary
      // read letter by letter
      // set c 
        if (c != '\n')
        {
            if (cursor -> children[c] == NULL)
               { cursor -> children[c] = malloc(sizeof(node)); }
            cursor = cursor -> children[c];
        }
        else if (c == '\n')
        {
             cursor -> is_word = true;
             cursor = root;
         }

    }

I have checked with GDB that k is correct (when word is cat k=2). Is the problem with CHECK or LOAD?

Please help I have been stuck on this for a few days!!

1
  • @ronga. The only parts of load() I left out is what I've added as comments. And none of it has any code for the trie (it's all about getting c).
    – Owly
    Nov 25 '15 at 11:08
1
  1. It seems you forgot to initialize your children array to NULL, which is why GDB shows you a segfault occurring there. While you're at it, you might want to initialize is_word to false as well. Finally, and this is just a matter of good coding practice, you might also want to have error handling each time you malloc, just to make sure malloc!=null.
  2. Also, it's not explicit in your code above, but is your check function iterating through each letter i of word, then going to children[i] if it exists?

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .