Working through the load portion of pset5. Everything compiles, but when I run valgrind it looks as if nothing is actually loading in, with the error of "null pointer passed as argument 1, which is declared to never be null."

In valgrind it is pointing to the following code within my hash function:

int hash(char *w)    // Hash function 
    hash_value = 1;
    int len = strlen(w);

However I think the error is actually taking place when inserting new values into the hashtable:

FILE* dict = fopen(dictionary, "r");
char word[LENGTH+1];
if (dict == NULL)
    fprintf(stderr, "Invalid Dictionary");
    return 1;

while (fscanf(dict, "%s", word) != EOF)
node* new_node = malloc(sizeof(node));
    // Check if malloc succeeeded
    if (new_node == NULL)
        return 1;
//new_node->word = word; //Insert Word into the nodes "word" section

//Hash value.
hash_value = hash(word);
strcpy(new_node->word, word);
 if (hashtable[hash_value] == NULL)
        hashtable[hash_value] = new_node;
        new_node->next = NULL;
        new_node->next = hashtable[hash_value];
        hashtable[hash_value] = new_node;

Do I have to do something different since I'm inserting into a hashtable? I initialize hashtable earlier on as follows:

node* hashtable[15625]; //Number of buckets for hashtable 

Any hints or pointers appreciated!

char *word = NULL;

while (fscanf(dict, "%s", word) != EOF)

The problem lies with word. It's a pointer to NULL. Next, the fscanf does a read and stores it at NULL, the infinite bit bucket. In other words, it discards it.

Either space for the read has to be malloc'd and the address stored in word, or, a different approach, create a char array large enough to hold any word plus the end of string marker.

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

  • Updated with more code to show where I initialize word. In the while loop, word should refer to each word in the dictionary, dict, which is then passed to the Hash function (which will be read as "w") for indexing, then placed into the appropriate hashtable. Am I using the while loop incorrectly here? – Jake Jul 11 '18 at 3:47
  • I'm running $ ./speller texts/lalaland.txt It looks like the first line of lalaland is actually a blank value - would this read as NULL? If so - would that mean I'd need to figure a way to skip over those empty values? – Jake Jul 11 '18 at 4:04
  • ok - edited in char *word = NULL; for char word[LENGTH+1]; This should have fscanf store word into that array locally, which is then copied into the node vis strcpy, right? Still having the same issue, however. – Jake Jul 11 '18 at 4:12
  • I'd have to test the code. If you want, I'm also on Slack. You could send me your complete code in a private message over there and I'll look at it later. cs50.edx.org/slack – Cliff B Jul 11 '18 at 4:20

You must log in to answer this question.

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