0

'''// Implements a dictionary's functionality

#include <stdbool.h> #include <stdio.h> #include <string.h> #include <stdlib.h> #include <ctype.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 = 800000;

// Hash table node *table[N];

//to keep track of the dictionary's size int dictionarySize = 0;

// Returns true if word is in dictionary, else false bool check(const char *word) { //get the index of the word int hashIndex = hash(word);

node *curser = table[hashIndex];

//checking the word with the table if it exists
while(true)
{
    if(strcmp(curser->word, word))
    {
        return true;
    }
    else
    {
        curser = curser->next;
    }

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

}

}

// Hashes word to a number unsigned int hash(const char *word) { long sum = 0;

for (int i = 0; i < strlen(word); i++)
{
    sum += tolower(word[i]);
}

return sum % N;

}

// Loads dictionary into memory, returning true if successful, else false bool load(const char *dictionary) { // TODO //fopen the file (check if its a null to end the function because the file didnt open) FILE *file = fopen(dictionary, "r");

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

//character array to read words into
char words[LENGTH + 1];

//fscanf in the while loop unti till it returns eof
while(fscanf(file, "%s", words) != -1)
{
    //making a new node
    node *n = malloc(sizeof(node));

    //checking node is valid
    if(n == NULL)
    {
        return false;
    }

    //assigning word to node
    strcpy(n->word, words);
    n->next = NULL;

    //determin which hash index
    int hashIndex = hash(n->word);

    //assigning word to table, and assigning the pointer in correct manner (n points same way as table)
    n->next = table[hashIndex];
    table[hashIndex] = n;
    dictionarySize++;
}


fclose(file);
return true;

}

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

// Unloads dictionary from memory, returning true if successful, else false bool unload(void) {

for(int i = 0; i < N; i++)
{
    node *curser = table[i];
    node *temp = curser;

    while(curser != NULL)
    {
        curser = curser->next;
        free(temp);
        temp = curser;
    }
    
    if (curser == NULL && i == N - 1)
    {
        return true;
    }

}

return false;

} ''' i am getting segmentation faults, and 1 error when running valgrind. but i am still a beginner to understand what the hell valgrind is telling me. so any help is appreciated.

1 Answer 1

0

check the use of int for hashindex for a bucket size of 800000 (e.g. when loading dictionary and also in hashing function)

You must log in to answer this question.

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