2017-09-05 66 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++; 
}