0

I've tested my load function with both large and small dictionaries, and I get the same problem for each one - it loads the dictionary completely (I've checked with gdb) but then after the entire dictionary is loaded, the while loop runs again to create a new word (that isn't there) and there's a segmentation fault. I'm assuming there's something wrong with the loop condition, but I can't figure out what. I've tried using a for loop instead, but I have the same problem.

Here is load:

bool load(const char* dictionary)
{
    // open file
    FILE* dic = fopen(dictionary, "r");

    // check if file is null
    if (dic == NULL)
    {
        printf("Could not load dictionary.\n");
        return false;
    }

    for (int i = 0; i < 26; i++)
    {   
        hashtable[i] = NULL;   
    }

    // create node and scan word
    while (!feof(dic))
    {
        node* new_node = malloc(sizeof(node));
        new_node->next = NULL;

        fscanf(dic, "%s", new_node->word);

        // create key
        int key = hashvalue(new_node->word);

        // first time or linked list;
        if (hashtable[key] == NULL)
        {
            hashtable[key] = new_node;
        }
        else
        {
            new_node->next = hashtable[key];
            hashtable[key] = new_node;
        }
        dic_size++;
    }

    return true;
}

1 Answer 1

0

The problem is in your structure. You test for EOF at the start of the loop, AND THEN you create another node AND THEN do another read. At the end of the dictionary file, that means that you've hit the EOF and try to make one more pass through the rest of the while loop, even though the dictionary file has been exhausted, before coming back to the beginning and detecting the EOF.

You need to do the read in the while loop setup statement and detect an EOF condition at the same time. (Read the spec on fread and you'll figure it out.)

If this answers your question, please click on the check mark to accept. Let's keep up on forum maintenance. ;-)

You must log in to answer this question.

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