I have been stuck here for several days. After loading 52209 words, I keep encountering Segmentation fault (core dumped). I think that I am consuming memory unnecessarily somewhere in the code, but I am unsure where.
I get the Segmentation fault (core dumped) error at this line in the load function
node *n = malloc(sizeof(node));
// Implements a dictionary's functionality
#include <ctype.h>
#include <stdbool.h>
#include <string.h>
#include <strings.h>
#include <stdio.h>
#include <stdlib.h>
#include "dictionary.h"
// 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 = 676;
// Hash table
node *table[N];
// word counter
int words = 0;
// Returns true if word is in dictionary, else false
bool check(const char *word)
{
node *n = table[hash(word)];
while(n != NULL)
{
if (strcasecmp(n -> word, word) ==0)
{
return true;
}
n = n ->next;
}
//strcasecmp(s1, s2) == 0
return false;
}
// Hashes word to a number
unsigned int hash(const char *word)
{
// TODO: Improve this hash function
if (strlen(word) == 1)
{
return toupper((word[0]) - 'A') * 26;
}
return toupper((word[0]) - 'A') * 26 + toupper(word[1]) - 'A';
}
bool isLoadedd = false;
// Loads dictionary into memory, returning true if successful, else false
bool load(const char *dictionary)
{
char dicword[LENGTH + 1];
FILE *dict = fopen(dictionary, "r");
if(dict == NULL)
{
return false;
}
while(fscanf(dict,"%s", dicword) != EOF)
{
node *n = malloc(sizeof(node));
if(n == NULL)
{
return false;
}
strcpy(n -> word, dicword);
n -> next = table[hash(dicword)];
table[hash(dicword)] = n;
words++;
};
isLoadedd = true;
return true;
}
// Returns number of words in dictionary if loaded, else 0 if not yet loaded
unsigned int size(void)
{
// TODO
if(isLoadedd)
{
return words;
}
return 0;
}
void freee();
// Unloads dictionary from memory, returning true if successful, else false
bool unload(void)
{
// TODO
for(int i = 0 ; i < N ; i++)
{
freee(table[i]);
if(table[0]== NULL && table[N-1]==NULL)
{
return true;
}
}
return false;
}
void freee(node *n)
{
if (n == NULL)
{
return;
}
freee(n->next);
free(n);
}
LENGTH is a constant 45
I tried to changeing the N value to 26 but thought maybe that will save memory but i got the same error.