我无法将数据加载到我的trie结构中。我一直有一个sgemenation错误。这与我的malloc有关吗?有人看到任何问题吗?
由于
/**
* 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;
}
答案 0 :(得分:1)
在将char用作数组中的索引之前,您不会检查char是否在范围内。范围a-z之外的任何字符都将导致缓冲区溢出。
在中减去97之后,将字符与已知字符常量进行比较。
您需要通过将NULL
分配给所有数组元素并将is_word
设置为false来初始化从malloc返回的内存。
只需看一眼代码,我就可能错过了其他错误。