I am currently trying to master speller but getting an error in one specific line when I run valgrind. It mentions this line:
n ->next = table[index];
I have no idea why. It says invalid read of size 8. (Process terminating with default action of signal 11 (SIGSEGV) ==6596== Access not within mapped region at address 0x5F98F0)
Also I am wondering if it is necessary to initialize my hash table, as I have done so at the very top of my 'load' function.
Thank you for any answers.
// Implements a dictionary's functionality
#include <stdbool.h>
#include <stdio.h>
#include<stdlib.h>
#include<string.h>
#include <strings.h>
#include <ctype.h>
#include <math.h>
#include "dictionary.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 = 10000;
//global variable
int *count = NULL;
// Hash table
node *table[N];
// Hashes word to a number
unsigned int hash(const char *word)
{
long long sum = 0;
int len = strlen(word);
for (int i = 0; i < len; i++)
{
sum = sum + pow((word[i] - 96), i);
}
int checksum = sum % 10000;
return checksum;
}
// Loads dictionary into memory, returning true if successful else false
bool load(const char *dictionary)
{
for (int i = 0; i < N; i++)
{
table[i] = malloc (sizeof(node));
if (table[i] == NULL)
{
printf("ERROR: Could not allocate enough memory. /n");
return false;
}
table[i]->next = NULL;
}
FILE * dict = fopen(dictionary, "r");
if (dict == NULL)
{
return false;
}
char s[LENGTH+1];
while (fscanf(dict, "%s", s) != EOF)
{
node *n = malloc(sizeof(node));
if (n == NULL)
{
unload();
return false;
}
strcpy(n->word, s);
int index = hash(n ->word);
n ->next = table[index];
table[index] = n;
free(n);
}
fclose(dict);
return true;
}