加载功能trie分段故障

时间:2017-09-05 10:36:00

标签: c null segmentation-fault trie cs50

我一直在为我的加载功能获得段错误。

    bool load(const char *dictionary)
{
    //create a trie data type
   typedef struct node
   {
        bool is_word;
        struct node *children[27]; //this is a pointer too!  
   }node;

   //create a pointer to the root of the trie and never move this (use traversal *)
   node *root = malloc(sizeof(node));
   for(int i=0; i<27; i++)
   {
       //NULL point all indexes of root -> children
       root -> children[i] = NULL;
   }


   FILE *dptr = fopen(dictionary, "r");
   if(dptr == NULL)
   {
       printf("Could not open dictionary\n");
       return false;
   }



   char *c = NULL;


   //scan the file char by char until end and store it in c
   while(fscanf(dptr,"%s",c) != EOF)
   {
       //in the beginning of every word, make a traversal pointer copy of root so we can always refer back to root
       node *trav = root;

       //repeat for every word
       while ((*c) != '\0')
       {
        //convert char into array index
       int alpha = (tolower(*c) - 97);

       //if array element is pointing to NULL, i.e. it hasn't been open yet,
        if(trav -> children[alpha] == NULL)
            {
            //then create a new node and point it with the previous pointer. 
            node *next_node = malloc(sizeof(node));
            trav -> children[alpha] = next_node; 

            //quit if malloc returns null
            if(next_node == NULL)
                {
                    printf("Could not open dictionary");
                    return false;
                }

            }

        else if (trav -> children[alpha] != NULL)
            {
            //if an already existing path, just go to it
            trav = trav -> children[alpha];
            }   
       }
        //a word is loaded. 
        trav -> is_word = true;
   }
   //success
   free(root);
   return true;
}

我检查了在初始化期间是否正确地将新指针指向NULL。我有三种类型的节点:root,遍历(用于移动)和next_node。 (i。)我是否允许在对mallocing它们之前对节点进行空值? (ii。)另外,如果该节点在if语句中初始化和malloced,我如何释放'next_node'? node *next_node = malloc(sizeof(node));(iii。)如果我想将节点设置为全局变量,哪些应该是全局变量? (iv。)最后,我在哪里设置全局变量:在speller.c的主要内部,在main之外,还是在其他地方?这有很多问题,所以你不必回答所有这些问题,但如果你能回答那些问题,那就太好了!请在我的代码中指出任何其他特性。应该有很多。我会接受大多数答案。

1 个答案:

答案 0 :(得分:0)

分段错误的原因是你没有分配内存的指针“c”。

另外,在你的程序中 -

//scan the file char by char until end and store it in c
while(fscanf(dptr,"%s",c) != EOF)

一旦为指针c分配内存,c将保存从文件字典中读取的单词。 在您的代码中,您正在检查'\ 0'字符 -

   while ((*c) != '\0')
   {

但是你没有将c指针移动到指向字符串读取中的下一个字符,因为这个代码最终会在循环时执行无限循环。 愿你可以尝试这样的事情 -

char *tmp;
tmp = c;
while ((*tmp) != '\0')
{
     ......
     ......
     //Below in the loop at appropriate place
     tmp++;
}