0
bool load(const char *dictionary)
{
    FILE *dict = fopen(dictionary, "r");
    if (dict == NULL)
    {
    return false;
    }
    char word[LENGTH + 1];
    while (fscanf(dict, "%s", word) != EOF)
    {
    node *ptr = malloc(sizeof(node));
    if (ptr == NULL)
    {
        return false;
    }
    strcpy(ptr->word, word);
    int hash_int = hash(word);
    ptr->next = table[hash_int]->next;
    table[hash_int] = ptr;
    word_count++;
    }
    fclose(dict);
    return true;
}

debug50 says there's a problem with this block of code.

ptr->next = table[hash_int]->next;

My code gives segfault and I couldn't see why.Can you help me with that?

1

At a glance, your problem potentially lies here:

char *word[LENGTH + 1];

The array size binds more tightly than *, so you are declaring an array of LENGTH + 1 pointers to a char, which you are also not allocating memory for.

Try simply declaring an array of chars:

char word[LENGTH + 1];

(And obviously remove the dereferencing operator where you pass word to various functions.)

1
  • Still doesn't work. I've updated the code. – exdeval Nov 30 '20 at 9:56
0
ptr->next = table[hash_int]->next;

I solved the problem, if ptr is the first element of table[hash_int], that means table[hash_int]->next does not exist. This causes the segfault. I solved the problem with these line of codes.

    if (table[hash_int] != NULL)
    {
    ptr->next = table[hash_int]->next;
    table[hash_int] = ptr;
    }
    else
    {
        table[hash_int] = ptr;
    }
2
  • While this will avoid the segfault, make sure you think about the logic. If you set ptr->next to table[hash_int]->next, what happens to the entry table[hash_int] was actually pointing to? – Sentox Nov 30 '20 at 17:28
  • You're right, I'll update the code. Thanks. – exdeval Dec 1 '20 at 19:02

You must log in to answer this question.

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