0

i couldnt find answer to my segmentation fault in load, please help.

 typedef struct node
 {
 bool is_word;
 struct node*next_char[27];
 }node;

struct node *root_ptr;

/**
* Returns true if word is in dictionary else false.
*/
bool check(const char *word)
{
// TODO
return false;
}

 //make new node and initialize to NULLs
 struct node*gnew_node(void)
 {
struct node*children=NULL;
children=(struct node*)malloc(sizeof(struct node));
if(children)

children->is_word=false;
for(int i=0;i<27;i++)

   children->next_char[i]=NULL;

return children;

 }
 /**
 * Loads dictionary into memory. Returns true if successful else false.
  */
 bool load(const char *dictionary)
 {
  // TODO
  root_ptr=(struct node*)malloc(sizeof(struct node));
 struct node *trav=root_ptr;
 FILE *fp=fopen(dictionary,"r");
 if(fp==NULL)
 {
    printf("dictionary failled to load\n");
    unload();
    return false;
   }

     //scan dictionary word by word
         char c;
     while((c=fgetc(fp))!=EOF)
     {
    if(c=='\n')
       {
        trav->is_word=true;
        trav=root_ptr;

       }
    else if(c=='\'')
    {
     trav=trav->next_char[26];   
    }
    else
    {
     int INDEX=(tolower(c))-'a';
     if(!trav->next_char[INDEX])
        {

         trav->next_char[INDEX]=gnew_node();
        }
         trav=trav->next_char[INDEX];
    }

    }

      fclose(fp);
     return true;
  }

    /**
  * Returns number of words in dictionary if loaded else 0 if not yet 
  loaded.
 */
 unsigned int size(void)
 {
  // TODO

   return false;
 }

 /**
  * Unloads dictionary from memory. Returns true if successful else false.
  */
 bool unload(void)
 {
  // TODO
  struct node* Pnode=root_ptr;

  for(int k=26;k>=0;k--)
  {
   if(Pnode->next_char[k]!=NULL)
   {
   free(Pnode->next_char[k]);
   }
  }

    free(root_ptr);
    return true;

}

0

You should get a segfault on load if your dict contains words with apostrophes.

Don't trav=trav->next_char[26] without having checked trav->next_char[26] is not NULL. You could combine those two paths, and just set INDEX to 26 if it's an apostrophe.

And your unload won't work. You'd have to unload a node's children before you unload the node itself, but those children might have children on their own. Recursion can solve this easily (otherwise you'd have to implement your own stack).

You must log in to answer this question.

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