this is my code so far for pset5. I would appreciate giving me hints about my erros. I also get a segmentation fault. thanks.
when I implemented load and check only, it seemed to load the text and stop, didn't know if that meant the check function didn't work. then after implementing size and unload, I get segmentation fault, of the text still loads.
This is my dictionary.c file:
/****************************************************************************
* dictionary.c
*
* Computer Science 50
* Problem Set 5
*
* Implements a dictionary's functionality.
***************************************************************************/
#include <stdbool.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <ctype.h>
#include "dictionary.h"
node* hashtable[26] = {0};
int count = 0;
/**
* Returns true if word is in dictionary else false.
*/
bool check(const char* word)
{
int n = strlen(word);
int found = 0;
char wword[LENGTH + 1];
node* new_cursor = NULL;
for (int i = 0; i < n; i++)
{
wword[i] = tolower(word[i]);
}
wword[n] = '\0';
int position = (tolower(wword[0]) - 'a') % 26;
if (hashtable[position] == NULL)
return false;
else
{
new_cursor = hashtable[position];
while (new_cursor->next != NULL)
{
if (strcmp (new_cursor->word, wword) == 0)
{
found++;
return true;
}
new_cursor = new_cursor->next;
}
}
if (strcmp (new_cursor->word, wword) != 0)
return false;
else
return true;
}
/**
* Loads dictionary into memory. Returns true if successful else false.
*/
bool load(const char* dictionary)
{
FILE* fp = fopen(dictionary, "r");
if (fp == NULL)
{
printf("Couldn't open dictionary\n");
return false;
}
node* new_node = NULL;
while(!feof(fp))
{
new_node = malloc(sizeof(node));
fscanf(fp, "%s", new_node->word);
int index = 0;
index = (tolower(new_node->word[0]) - 'a') % 26;
if ((hashtable[index]) == NULL)
{
hashtable[index]->next = new_node;
count++;
}
else
{
new_node->next = hashtable[index];
hashtable[index] = new_node;
count++;
}
}
fclose(fp);
return true;
}
/**
* Returns number of words in dictionary if loaded else 0 if not yet loaded.
*/
unsigned int size(void)
{
return count;
}
/**
* Unloads dictionary from memory. Returns true if successful else false.
*/
bool unload(void)
{
for (int i = 0; i < 26; i++)
{
node* freenode = NULL;
node* tmp = NULL;
freenode = hashtable[i];
while (freenode != NULL)
{
tmp = freenode;
freenode = freenode->next;
free(tmp);
}
free(freenode);
}
return true;
}