I started working on this yesterday. It compiles but whenever I run it with
./speller texts/lalaland.txt
I get this result:
WORDS MISSPELLED: 17134
WORDS IN DICTIONARY: 143091
WORDS IN TEXT: 17756
TIME IN load: 0.04
TIME IN check: 8.41
TIME IN size: 0.00
TIME IN unload: 0.00
TIME IN TOTAL: 8.45
As you can see it takes a stupid amount of time in "check" and no time in "size" or "unload". I'm almost certain there's nothing wrong with my check function though. Any assistance would be appreciated.
// Implements a dictionary's functionality
#include <stdlib.h>
#include <ctype.h>
#include <string.h>
#include <stdbool.h>
#include <cs50.h>
#include <stdio.h>
#include "dictionary.h"
#include <strings.h>
unsigned int counter;
unsigned int i;
// Represents a node in a hash table
typedef struct node
{
char word[LENGTH 1];
struct node *next;
}
node;
// TODO: Choose number of buckets in hash table
const unsigned int N = 26;
// Hash table
node *table[N];
// Returns true if word is in dictionary, else false
bool check(const char *word)
{
i = hash(word);
node *cursor = table[i];
while (cursor != 0)
{
if (strcasecmp(cursor->word, word) == 0)
{
return true;
}
cursor = cursor->next;
}
return false;
}
// Hashes word to a number
unsigned int hash(const char *word)
{
int value;
for (int j = 0; j< strlen(word); j )
{
value = value tolower(word[j]);
}
return (value % N);
}
// Loads dictionary into memory, returning true if successful, else false
bool load(const char *dictionary)
{
// TODO
FILE* file = fopen(dictionary, "r");
if (file == NULL)
{
return false;
}
char word[LENGTH 1];
while (fscanf(file, "%s", word) != EOF)
{
node *new = malloc(sizeof(node));
if (new == NULL)
{
return false;
}
strcpy(new->word, word);
new->next = NULL;
i = hash(word);
new->next = table[i];
table[i] = new;
counter ;
}
fclose(file);
return true;
}
// Returns number of words in a dictionary if loaded, else 0 if not yet loaded
unsigned int size(void)
{
if (counter != 0)
{
return counter;
}
return 0;
}
// Unloads dictionary from memory, returning true if successful, else false
bool unload(void)
{
for (int j = 0; j < N; j )
{
node *head = table[j];
node *cursor = head;
node *temp = head;
while(cursor != NULL)
{
cursor = cursor->next;
free(temp);
temp = cursor;
}
if (cursor == NULL)
{
return true;
}
}
return false;
}
CodePudding user response:
There is a problem with the hash
function. valgrind will complain about an unitialised value in hash; specifically value
. Because value
is not initialized, it will have the value that is stored in the memory that is assigned to it. Unpredictable results ensue.
There is also a problem with unload. Once the first node is freed, program will return true
from the unload function. However, it hasn't freed any other nodes.