Can anyone help with segmentation fault. I have tried running debug50 and aparently the fault hits at line "if (head -> next != NULL)" in the load function. Aparently "table" is null despite already being declared.
// Implements a dictionary's functionality
#include <stdbool.h>
#include <cs50.h>
#include <stdlib.h>
#include <stdio.h>
#include "dictionary.h"
#include <string.h>
#include <ctype.h>
#define HASHTABLE_SIZE 10000
unsigned int hash(const char *hash_this);
// Represents a node in a hash table
typedef struct node
{
char word[LENGTH + 1];
struct node *next;
}
node;
int values = 0;
// Number of buckets in hash table
const unsigned int N = 10000;
// Hash table
node *table[N];
// Returns true if word is in dictionary, else false
bool check(const char *word)
{
// TODO
char low_word[LENGTH + 1];
for (int i = 0; i < LENGTH; i++)
{
if (isalpha(word[i]))
{
low_word[i] = tolower(word[i]);
}
}
int hash_index = hash(low_word);
node *cursor = table[hash_index] -> next;
if (cursor -> next != NULL)
{
while (cursor -> next != NULL)
{
if (cursor -> word == low_word)
{
return true;
}
else
{
cursor = cursor -> next;
}
}
return false;
}
else
{
return false;
}
}
// Hashes word to a number
unsigned int hash(const char *hash_this)
{
unsigned int hash = 0;
for (int i = 0, n = strlen(hash_this); i < n; i++)
{
hash = (hash << 2) ^ hash_this[i];
}
return hash % HASHTABLE_SIZE;
}
// Loads dictionary into memory, returnina true if successful, else false
bool load(const char *dictionary)
{
// TODO
FILE *dict = fopen(dictionary, "r");
if (dict == NULL)
{
printf("Invalid Dictionary\n");
return false;
}
values = 0;
char word[LENGTH + 1];
while (fscanf(dict, "%s", word) != EOF)
{
for (int i = 0; i < LENGTH; i++)
{
if (isalpha(word[i]))
{
word[i] = tolower(word[i]);
}
}
node *newNode = malloc(sizeof(node));
if (newNode == NULL)
{
return false;
}
strcpy(newNode -> word, word);
newNode -> next = NULL;
int hash_index = hash(newNode -> word);
node *head = table[hash_index];
if (head -> next != NULL)
{
newNode -> next = head -> next;
}
head -> next = newNode;
values++;
}
return true;
}
// Returns number of words in dictionary if loaded, else 0 if not yet loaded
unsigned int size(void)
{
// TODO
return values;
}
// Unloads dictionary from memory, returning true if successful, else false
bool unload(void)
{
// TODO
for (int i = 0; i < N; i++)
{
node *cursor = table[i] -> next;
if (cursor != NULL)
{
node *tmp = cursor;
cursor = cursor -> next;
free(tmp -> next);
}
}
if (sizeof(table) == sizeof(node[N]))
{
return true;
}
else
{
return false;
}
}