0

I wrote the load code for pset5 which compiles but when I execute speller.c it says "Could not load dictionary". I have used both my own dictionary text file and the dictionary at home/cs50/pset5/dictionaries/large.

This is really driving me crazy. My code is below. Any help would be greatly appreciated.

Thanks!

/**
* Loads dictionary into memory.  Returns true if successful else false.
*/
bool load(const char* dictionary)
{

int hashdex = 0; 

//open dictionary file
FILE* fptr = fopen(dictionary, "r"); 

if(fptr == NULL)
{
    printf("Could not load %s\n", dictionary); 
    return false; 
}

//make new node
node* newNode = malloc(sizeof(node)); 

if(newNode == NULL)
{
    printf("Out of heap memory.\n");
    fclose(fptr);
    return false;
}

while((fscanf(fptr, "%s", newNode->entry)) != EOF)
{
    hashdex = hash_it(newNode->entry); 

    if(table[hashdex] == NULL)
    {
        newNode->next = NULL; 
        table[hashdex] = newNode;
    }
    //collision, add to the beginning
    else
    {
        newNode->next = table[hashdex]->next;
        table[hashdex]->next = newNode; 
    }

}

free(newNode); 
fclose(fptr);   
return true;
}
1

I'm not sure why you're getting the 'could not load dictionary' message, I was not able to duplicate that. However, there is still a significant problem with this code.

The major problem is that the code is creating exactly one and only one node and reusing it for every word. As each word is read from the file, it overwrites the previous word in that node. Instead, the code needs to create/malloc a new node for every word read from the dictionary file. Once a word is written into its node, the node needs to be added to the tree.

There's a related problem. At the end of the load routine, free() is called, releasing the node. Since there's only one node, it will essentially delete the tree. After you fix the earlier problem, this will still be a problem because it will delete the node for the last word in the dictionary.

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

3
  • Thanks for the reply! I've fixed my code to reflect your suggestions. However, I'm still getting the "Could not load" message. I don't know why this is happening because fptr should not be NULL as far as I can tell. Can you think of any reason why I might still be getting that message? – grparker21 May 25 '16 at 0:36
  • not without seeing the updated code. – Cliff B May 25 '16 at 0:43
  • Ah I just realized my file paths were the problem! Everything works now. Thanks again! – grparker21 May 25 '16 at 0:49
0

It looks like you are only calling malloc once, so you are only being allocated a node once; I believe you want to allocate a new node for each word and then copy each word to the new node.

You must log in to answer this question.

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