When I run my load function with ./speller text, it reported segmentation fault. When I use valgrind to check, it told me that the problem in the two line:
char new_word[LENGTH + 1];
while(fgets(new_word, LENGTH + 1, fp) != NULL)
and large number of memory is allocated with 0 free. Can anyone point out the problem? Thanks in advance
This is what my entire code looks like:
bool load(const char* dictionary)
{
// Open the dictionary file
FILE* fp = fopen(dictionary, "r");
if (fp == NULL)
return 1;
//create a hash table and set heads to null
typedef struct node
{
char word[LENGTH + 1];
struct node* next;
}
node;
node* table[CAPACITY]
for (int i = 0; i < CAPACITY, i++)
table[i] = NULL;
//read through the dictionary
char* new_word[LENGTH + 1];
while (fgets(new_word, LENGTH + 1, fp) != NULL)
{
node* new_node = malloc(sizeof(node));
if (new_node == NULL)
return 2;
new_node->word = new_word;
//hash the new word
int hash = hash_fun(new_word);
//insert the new word to the local linked list
if (table[hash] == NULL)
{
new_node -> table[hash];
table_hash = new_node;
}
node* cursor = table[hash];
while (cursor != NULL)
{
node* pre = cursor;
cursor = cursor->next;
pre->next = new_node;
new_node->next = NULL;
return true;
}
}