0

I'm trying to load my dictionary into memory in order to program my spellchecker. While compiling "speller.c" works fine, my execution ./speller returns a seg fault and I just can't seem to get the hang of it.

Could you help me find my mistake?

bool load(const char *dictionary)
{
    // Initialize each value in hash table to NULL.
    for(int i = 0; i < HASH_SIZE; i++)
    {
        hashtable[i] = NULL;
    }   

    //open dictionary file and store in local pointer
    FILE *fp = fopen(dictionary, "r");
    if (fp == NULL)
    {
        printf("Could not open %s.\n", dictionary);
        unload();
        return 1;
    }

    //populate linkedlist with dictionary's words
    while(fscanf(fp, "%s" , buffer) != EOF)
    {
        //create new node & assign memory to it
        node *l_node = malloc(sizeof(node));
        l_node->next = NULL;

        //check if malloc successfully assigned memory to new node
        if(l_node == NULL)
        {
            unload();
            return false;
        }

        //copy current word of dictionary into current node
        strcpy(l_node->word, buffer);

        //hash function: modulo of first char in word provides index for hashtable array
        int bucket_index = hash_function(l_node->word);

        //fill node into linked list -> determine which bucket of hashtable to use EXAMPLE FOR FIRST LETTER!!
        if (hashtable[bucket_index] == NULL)
        {
            hashtable[bucket_index] = l_node;
        }
        else
        {
            node *current_first_element = hashtable[bucket_index];
            l_node->next = current_first_element;
            hashtable[bucket_index] = l_node;
        }
    }        
    return false;
}
1

You forget to fclose the dictionary, but else...

l_node->next = NULL; would be a bad idea before testing if l_node == NULL.

Make sure your buffer variable and word property both can handle a word of the maximum length (remember the final null terminator, so at least char[LENGTH+1]).

Also, ensure hash_function returns numbers in the right range for hashtable.

You can find the line responsible for the segfault by using debug50 and stepping through the code, line by line.

You must log in to answer this question.

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