0
// Implements a dictionary's functionality

#include <stdbool.h>
#include "dictionary.h"
#include <stdlib.h>
#include <stdio.h>
#include <string.h>
#include <strings.h>

// Represents a node in a hash table
typedef struct node
{
    char word[LENGTH + 1];
    struct node *next;
}
node;

int counter = 0;

// Number of buckets in hash table
const unsigned int N = 676;

// Hash table
node *table[N];

// Returns true if word is in dictionary else false
bool check(const char *word)
{
    int c = hash(word);
    node *cursor = malloc(sizeof(node));

    for(cursor = table[c]->next; cursor->next != NULL; cursor = cursor->next)
    {
        if(strcasecmp(word, cursor->word )==0 )
        return true;
    }

    return false;
}

// Hashes word to a number
unsigned int hash(const char *word)
{
    // TODO
    int i = word[0];
    int j = word[1];
    int k = (i*(31^0)) + (j*(31^1));
    int l = k%676;
    return l;
}

// Loads dictionary into memory, returning true if successful else false
bool load(const char *dictionary)
{
    FILE *file = fopen(dictionary , "r");
    if(file == NULL)
    {
        return false;
    }

    char *word = malloc(sizeof(char)*LENGTH + 1);

    while(fscanf(file, "%s", word ) != EOF)
    {
        fscanf(file, "%s", word);
        node *n = malloc(sizeof(node));

        if(n == NULL)
        {
            return false;
        }

       strcpy(n->word , word);
       unsigned int index = hash(n->word);
       n->next = table[index]->next;
       table[index]->next = n;
       counter++;
    }

    return true;
}

// Returns number of words in dictionary if loaded else 0 if not yet loaded
unsigned int size(void)
{
   return counter;
}

// Unloads dictionary from memory, returning true if successful else false
bool unload(void)
{
    // TODO
    for(int i = 0; i < N; i++)
    {
        node *cusor = table[i]->next;
        node *temp = cusor;
        while(cusor->next != NULL)
        {
            cusor = cusor->next;
            free(temp);
            temp = cusor;
        }
        return true;
    }

    return false;
}
1
  • 1
    Please try some debugging found here. Hopefully you can find the problem yourself. If not, you can edit the question with a narrower focus (ie on a specific function or better still a specific line) that is provoking the segfault. Then you can edit the question accordingly. Be sure it's formatted properly too! (In the edit screen, select the code, then click the {} button and voilá, code is formatted properly) – DinoCoderSaurus May 18 '20 at 16:19
-1

In your last unload function you are using

node *cusor = table[i]->next;

when table[I] in it self is a pointer.

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .