I'm writing a program that spell checks words, but my hash function is not returning the same number for the same words.
My question is how is my hash function not returning the same hash for the same input.
Here is a Minimal, Reproducible Example of my issue:
// Implements a dictionary's functionality
#define HASHTABLE_SIZE 65536
// 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 = HASHTABLE_SIZE;
// Hash table
node *table[N];
unsigned int totalWords = 0;
// Hashes word to a number
unsigned int hash(const char *word)
{
unsigned int hash_value;
for (int i=0, n=strlen(word); i<n; i++)
hash_value = (hash_value << 2) ^ word[i];
return hash_value % HASHTABLE_SIZE;
}
hash_value
in the hash function is uninitialized and it wreaks memory havoc, which causes unpredictable results. From the cited post:
unsigned int hash = 0;