2017-09-05 63 views
0

我不断收到我的加载函数的段错误。加载函数trie分段错误

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。我有三种类型的节点:根,遍历(移动)和next_node。 (i。)我可以在将它们分配给它们之前将节点清零吗? (ii。)另外,如果该节点在if语句中初始化并插入,则如何释放'next_node'? node *next_node = malloc(sizeof(node));(iii。)如果我想将节点设置为全局变量,哪些应该是全局变量? (iv。)最后,我在哪里设置全局变量:在speller.c的主体内,在其主体之外还是其他地方?这是很多问题,所以你不必回答所有问题,但如果你能回答答案,那将是很好的!请指出我的代码中的其他任何特性。应该有很多。我会接受大多数答案。

+0

你需要调试你的代码,所以你找出哪一行代码段错误的。您还需要在代码中进行错误处理和验证。例如这些行:'int alpha =(tolower(* c) - 97);如果(trav - > children == NULL)'不是你可以做的事情,你必须知道你的输入是否有效,所以你必须检查'alpha'是否'> = 0'和<27 ''在你可以继续使用它并将其用作'trav - > children'的索引' – nos

+1

'char * c = NULL;'''''''''''''''''''''''''''''''' – Matt

+0

'fscanf'想要一个指向一个地方的指针来存储传入的数据。你已经将'c'设置为'NULL'并将其传递给'fscanf',所以当你读取一行时,它试图通过空指针写入。创建一个256字符的行缓冲区,并将其作为参数传递给'fscanf'。 –

回答

0

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

而且,在你的程序 -

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

一旦你分配内存的指针C,C将举行从文件中读取字典的单词。 下面在你的代码,你检查“\ 0” character-

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

但你不动的C指针指向下一个字符字符串中,因为此代码最终会执行无限的读while循环。 愿你可以尝试像这个 -

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