0

This is the second time I started the pset5 from scratch. This time, when I am running load for small dictionary i get the message that text couldn't be found. When I run the function for large dictionary i get a segmentation error for line 82: head=head->next. Can anyone give me a clue where is the mistake? Thanks in advance.

 #define SIZE 65599

//defining node structure 

typedef struct node

{

    char word[LENGTH+1];
    struct node *next;

} node; 

//defining hash function

int hash_function (char *key)

{
    unsigned int hash=0; 

    for (int i=0; key[i]; i++)
    {
        hash=hash*SIZE+key[i]; 
    }
    return (hash % 1024);
}

//defining hash table and word count

node *hash_table[500];

int word_count; 

/**
 * Returns true if word is in dictionary else false.
 */

bool check(const char* word)
{
    // TODO
    return false;
}

/**
 * Loads dictionary into memory.  Returns true if successful else false.
 */

bool load(const char* dictionary)

{
    FILE *fp = fopen(dictionary, "r");

    if (fp==NULL)
    {
        printf("File dictionary cannot be opened\n");
        return false;
    }

    while(!feof(fp))
    {
        node *new_node=malloc(sizeof(node));
        fscanf(fp, "%s", new_node->word); 
        int h = hash_function(new_node->word);
        word_count++;

        if (hash_table[h]==NULL)
        {
            hash_table[h]=new_node;
            new_node->next=NULL;
        }
        else
        {
            node *head=malloc(sizeof(node)); 
            head=hash_table[h];
            while (head!=NULL)
            {
                head=head->next; 
            }
            new_node->next=head; 
            hash_table[h]=new_node;
        }
    }

    if (feof(fp))
    {
        fclose(fp); 
        return true;
    }

    fclose(fp); 
    return false;
}
0

You're creating an array of size 500 for your hash table:

node *hash_table[500];

What do you think will happen when you try to access hash_table[h], when h has been defined in a function that returns

return (hash % 1024);

By the way, this is never really a good idea:

while(!feof(fp))

The eof indicator is only set after the end of file has been reached, and it's not reached until after some function (fscanf in this case) attempts to read the file. You will end up reading some garbage, storing it, and increasing the word counter by one too many.

You must log in to answer this question.

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