2016-08-31 5 views
-2

У меня возникли проблемы с загрузкой данных в мою структуру trie. Я продолжаю испытывать недостаток. Это связано с моим malloc? Кто-нибудь видит какие-либо проблемы?Загрузка структуры данных trie в C-pset5 cs50

Благодаря

/** 
* dictionary.c 
* 
* Computer Science 50 
* Problem Set 5 
* 
* Implements a dictionary's functionality. 
*/ 

#include <stdbool.h> 
#include <stdio.h> 
#include <stdlib.h> 
#include <ctype.h> 
#include <string.h> 
#include "dictionary.h" 


#define ASCII_OFFSET 97; 

/** Node of the data structure used to store the dictionary key words 
* Data Structures Type is Tries 
* Includes a bool to indicate if the current node is the end of a word 
* A pointer to the nodes child node 
*/ 
typedef struct node 
{ 
    bool is_word; 
    struct node* children[27]; 
} 
node; 
node* rootNode; 
node* nextNode; 

//Variable to track the size of the dictinoary 
int wordCount = 0; 

/** 
* Returns true if word is in dictionary else false. 
*/ 

bool check(const char* word) 
{ 
    //Get words length 
    int wordLength = strlen(word); 

    for(int i = 0; i < wordLength; i++) 
    { 
     //taking the character we need to check 
     int charToCheck = tolower(word[i]) - ASCII_OFFSET; 

     //Checking to see if the char exists in the data strucutre, Trie; 
     if(nextNode->children[charToCheck] == NULL) 
     { 
      return false; 
     } 

     //Advance the next node down the trie 
     nextNode = nextNode->children[charToCheck]; 
    } 

    nextNode = rootNode; 
    //Return what is_word return 
    return nextNode->is_word; 
} 

/** 
* Loads dictionary into memory. Returns true if successful else false. 
*/ 

bool load(const char* dictionary) 
{ 
    //Open dict.. file to read 
    FILE* file = fopen(dictionary,"r"); 

    //Check if the dict.. exsists! 
    if(file == NULL) 
    { 
     return false; 
    } 

    //Creating the first node in our data strucutre 
    rootNode = malloc(sizeof(node)); 
    nextNode = rootNode; 

    //Get character to store 
    int character = fgetc(file) - ASCII_OFFSET; 

    //Go through the dict... file 
    while(character != EOF) 
    { 
     //Go through each word in the file 
     while(character != '\n') 
     { 
      //Add into our data structure 
      if(nextNode->children[character] == NULL) 
      { 
       //Create memory inorder to insert the next node 
       nextNode->children[character] = malloc(sizeof(node)); 
       nextNode = nextNode->children[character]; 
      }else { 
       nextNode = nextNode->children[character]; 
      } 

      //advance character to next 
      character = fgetc(file) - ASCII_OFFSET; 
     } 

     //advance character to next word 
     character = fgetc(file) - ASCII_OFFSET; 

     //Set the last node loaded to is_word to track the end of each word 
     nextNode->is_word = true; 
     wordCount++; 
     nextNode = rootNode; 
    } 


    fclose(file); 
    return true; 
} 

/** 
* Returns number of words in dictionary if loaded else 0 if not yet loaded. 
*/ 

unsigned int size(void) 
{ 
    return wordCount; 
} 

/** 
* Unloads dictionary from memory. Returns true if successful else false. 
*/ 

bool unload(void) 
{ 
    for(int i = 0; i < 26; i++) 
    { 
     if(nextNode->children[i] != NULL) 
     { 
      nextNode = nextNode->children[i]; 
      unload(); 
     } 
    } 

    free(nextNode); 
    return true; 
} 
+1

Поздравляем, вы вставили задание в Интернет. Каков был ваш вопрос? – Useless

+0

Извините, у меня возникли проблемы с загрузкой моего трюка, он продолжал получать ошибку сегментации. – menan

+0

Что такое «trie»? (Ssh, не помогите OP!) – Koshinae

ответ

1
  1. Вы не проверить, что символ находится в диапазоне, прежде чем использовать его в качестве индекса в массиве. Любой символ вне диапазона a-z вызовет переполнение буфера.

  2. Вы сравниваете символ с известными константами символов после вы вычитали 97 из него.

  3. Нужно инициализировать память, возвращенную из malloc, назначив NULL всем элементам массива и установив is_word в значение false.

Просто коротко взглянул на код, поэтому я, возможно, пропустил дополнительные ошибки.

+0

Вы также должны использовать calloc вместо malloc, потому что вы проверяете NULL, но malloc не дает вам определенного значения памяти. – maxbit89

+2

@ maxbit89 Вы поднимаете действительную точку. Я не думаю, что «NULL» должен быть «0» стандартным (хотя «все» реализации кажутся ему «0»), поэтому я решил рекомендовать явно установить указатели на «NULL» вместо. –

+0

Да, он не определен в Стандарте, но он хорошо используется ^^. См. Также: http://stackoverflow.com/questions/9894013/is-null-always-zero-in-c – maxbit89