2015-11-03 12 views
-1

這是爲我的CS50作業。我必須做一個拼寫檢查器,將字典加載到數據結構中。直到文件大小增加纔會發生段錯誤。有人會關心在我的代碼中識別可能導致段錯誤的原因嗎?

//Trie structure 
typedef struct node { 

    bool is_word; 
    struct node* children[27]; 
}node; 

node* root; 

// maximum length for a word 
#define LENGTH 45 
//global counter for total words in dic 
int SIZE = 0; 

將字典加載到內存中。

bool load(const char* dictionary) 
{ 
    //Open dictionary file && safecheck 
    FILE* d_file = fopen(dictionary,"r"); 
    if(d_file == NULL) { return false; } 

    //allocate space for the first node 
    root = calloc(1,sizeof(node)); 

    //string buffer 
    char word[SIZE+1]; 
    //loop through each word of the dictionary and store it to word 
    while(fscanf(d_file,"%s\n",word)!=EOF){ 
     //navigation node steping further into trie 
     node* nav = root; 
     int word_length = strlen(word); 
     //Iterate through each letter in a word 
     for(int i=0;i<word_length;i++){ 
      int letter_pos = tolower(word[i]) - 'a'; 
      //check if letter node exists 
      if(nav->children[letter_pos]==NULL){ 
       //create node for a letter 
       node* l_node = calloc(1,sizeof(node)); 
       if(l_node == NULL) { return false; } 
       nav->children[letter_pos] = l_node; 
      } 
      //proceed to the next node 
      if(i < word_length-1) 
       nav = nav->children[letter_pos]; 
     } 
     //set word to true; 
     if(nav->is_word != true){ 
      nav->is_word = true; 
      // counter for total words in the dictionary 
      SIZE++; 
     } 
    } 
    fclose(d_file); 
    return true; 
} 
+3

如果遇到分段錯誤等崩潰,應該在調試器中運行以捕獲崩潰,因爲調試器將停在崩潰位置。在調試器中,您可以將函數調用堆棧放到您的代碼中(如果它尚未存在)並檢查變量的值。至少,你應該編輯你的問題,並告訴我們崩潰發生的地方和變量值。 –

+1

感謝您的建議,我首先嚐試調試,這只是我需要更多練習。一旦錯誤發生並且調試器停止,我不知道如何通過函數。我會看看它現在:) –

回答

0

我不知道這是主要的問題,但是這部分代碼在穩健性極度缺乏:

 int letter_pos = tolower(word[i]) - 'a'; 

如果letter_pos無效在這一點上(例如,因爲word[i]不是一封信),那麼所有後續操作都將導致UB。

我想至少是添加assert這裏:

 int letter_pos = tolower(word[i]) - 'a'; 
     assert(letter_pos >= 0 && letter_pos < sizeof(nav->children)/sizeof(nav->children[0])); 

由於您的數組大小是27我猜你想使用非字母字符的最後一個元素,所以你可能要使代碼更像這樣:

 int letter_pos; 
     if (isalpha(word[i]))     // if 'A'..'Z' or 'a'..'z' 
      letter_pos = tolower(word[i]) - 'a'; // index = 0..25 
     else 
      letter_pos = 'z' - 'a' + 1;   // index = 26 
     assert(letter_pos >= 0 && letter_pos < sizeof(nav->children)/sizeof(nav->children[0])); 
+0

謝謝,很多是這樣! :) –

相關問題