I am tackling CS50 Pset 5 speller.c.

I successfully make speller.c, but when I tried to run the program, it showed "Segmentation fault".

So I run valgrind, and the result is:

==14531== Invalid read of size 4
==14531==    at 0x59DB0CD: __isoc99_fscanf (isoc99_fscanf.c:30)
==14531==    by 0x422597: load (dictionary.c:48)
==14531==    by 0x420912: main (speller.c:40)
==14531==  Address 0x0 is not stack'd, malloc'd or (recently) free'd

My code in dictionary.c from line 46 is below:

//scan dictionary word by word
//dword: dictionary words, which is different from the words to be checked
while(fscanf(dic, "%s", &dword) != EOF)
    //malloc a node * for each new word
    node *new_node = malloc(sizeof(node));

    //checck whether run out of memory
    if (new_node == NULL)
        return false;
    //copy word into node
    strcpy(new_node -> dword, &dword);

    //Decide which bucket to put a new node. make Hash function to hash word
    //scanf(word, "%1c", first)
    code = hash(&dword);

    //insert into the bucket linklist
    new_node -> next = hashtable[code];
    hashtable[code] = new_node;
dictionary = NULL;
return true;

I struggle to figure out what's wrong, but I cannot. T-T

Please help me!

Thank you soooooooo much!! T-T (>人<)


The error message means that fscanf tried to dereference a NULL pointer. Which means you either did not correctly fopen the dictionary (including the check for NULL, in which case you would have to abort load function and return false;), or you are not providing the space for the characters to read. I assume you are using something like char dword[LENGTH + 1]; above your loop.

Oh, and do not free nodes in load, they are still in use. free them in unload instead, walking all the linked lists you built.

  • Please note that in case of char *dword = malloc((LENGTH + 1) * sizeof(char));, you would have to pass dword, and not &dword (which is the memory address of the pointer, not where it is pointing to), while char dword[LENGTH + 1]; would work with or without the & (both lead to the same pointer being passed). – Blauelf Oct 10 '18 at 13:56
  • Thank you for answering. I am a new learner. Could you specify how to provide the space for the characters to read? I tried char *dword = malloc(LENGTH * sizeof(char) +1); But it did not work... So confusing... – Y.J.Zhang Oct 10 '18 at 14:01
  • Allocation on heap, as you do it, should work if you pass dword, not &dword. But an array on stack would be what I would do instead. – Blauelf Oct 10 '18 at 14:24

You must log in to answer this question.

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