i'm not sure why this happens when I execute the code. The program seems to never end as if it's running an infinite loop. When I run valgrind on it misspelled words keep spewing out and it gives me a message "More than 10000000 total errors detected. I'm not reporting any more. ==1331== Final error counts will be inaccurate. Go fix your program!" Any help would be appreciated. Thanks!
// Implements a dictionary's functionality
#include <stdbool.h>
#include "dictionary.h"
#include <strings.h>
#include <string.h>
#include <stdio.h>
#include <stdlib.h>
#include <ctype.h>
// Represents a node in a hash table
typedef struct node
{
char word[LENGTH + 1];
struct node *next;
}
node;
// Number of buckets in hash table
const unsigned int N = 40;
// Hash table
node *table[N] = {NULL};
//counter for load
int count = 0;
// Returns true if word is in dictionary else false
bool check(const char *word)
{
int num = 0;
num = hash(word);
node* traversal = malloc(sizeof(node));
traversal = table[num];
while(traversal != NULL)
{
if(strcasecmp(traversal->word, word) == 0)
{
return true;
}
traversal = traversal->next;
}
free(traversal);
return false;
}
// Hashes word to a number
unsigned int hash(const char *word)
{
unsigned int hash = 5381;
int c;
while ((c = *word++))
{
/* hash * 33 + c */
hash = ((hash << 5) + hash) + tolower(c);
}
return hash % N;
}
// Loads dictionary into memory, returning true if successful else false
bool load(const char *dictionary)
{
unsigned int num = 0;
char buffer[LENGTH + 1];
//Open dictionary file
FILE *ptr = fopen(dictionary, "r");
if(ptr == NULL)
{
printf("Can't open dictionary");
return false;
}
//Read string from file one at a time
while(fscanf(ptr,"%s",buffer) != EOF)
{
//Create a new node for each word
node* n =malloc(sizeof(node));
if(n != NULL)
{
strcpy(n->word,buffer);
n->next = NULL;
}
//Hash word to obtain a hash value for each word
num = hash(buffer);
**if(table[num] != NULL)
{
n->next = table[num];
}
table[num] = n;**
//keeps track of how many words in dictionary
count++;
free(n);
}
fclose(ptr);
return true;
}
// Returns number of words in dictionary if loaded else 0 if not yet loaded
unsigned int size(void)
{
if(count > 0)
{
return count;
}
else return 0;
}
// Unloads dictionary from memory, returning true if successful else false
bool unload(void)
{
node* cursor = NULL;
node* temp = NULL;
for(int i = 0; i<N; i++)
{
cursor = table[i];
temp = cursor;
while(cursor != NULL)
{
temp = cursor->next;
free(cursor);
cursor = temp;
}
}
return true;
}
table[num] = n
andn->next = table[num]
– DinoCoderSaurus Jul 2 '20 at 20:48free(n);
right? Poof. The word is gone, the pointer is gone......... – DinoCoderSaurus Jul 3 '20 at 14:09