0

I tried to implement Speller, but check 50 returns:

:( program is free of memory errors valgrind tests failed; rerun check50 with --log added to end of command for more information.

When I run valgrind it returns: ==20822== Invalid write of size 1 ==20822== at 0x422CD5: check (dictionary.c:98) ==20822== by 0x421373: main (speller.c:112)

Looks like you're trying to modify 1 byte of memory that isn't yours? Did you try to store something beyond the bounds of an array? Take a closer look at line 98 of dictionary.c.

My code:

// Returns true if word is in dictionary else false
bool check(const char *word)
{
    // TODO
    char *checkword = malloc(sizeof(LENGTH + 1));
    // Make a copy of the word for lowercases
    for (int i = 0; i < strlen(word) + 1; i++)
    {
        checkword[i] = tolower(word[i]); **<-----this is line 98**
    }
    // Get the pointer from the hashtable
    int y;
    y = hash(word);
    node *cursor = hashtable[y];
    while (cursor != NULL)
    {
        // Compare strings
        if (strcmp(checkword, cursor->word) == 0)
        {
            free(checkword);
            return true;
        }
        // If not the same word, go further down the linked-list
        cursor = cursor->next;
    }
    free(checkword);
    return false;
}

This is the first problem with the memory and I am thankful for any suggestions!

1

The problem is in the declarations:

char *checkword = malloc(sizeof(LENGTH + 1));

and

i < strlen(word) + 1;

Note that the length of the word array is LENGTH + 1, then the length of strlen (word) +1 is actually LENGTH +2, so you are trying to write one more byte in the checkword. If you want to write the character end of string in checkword, you must reserve more space with malloc, do not forget freed with free(), but I would use an array, and not malloc, in this case

1
  • I just came around to implement your suggestions, thank you so much! You have saved me from quite a bit of anguish! :D
    – Eliqwa
    May 4 '19 at 8:15

You must log in to answer this question.

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