0

I keep getting most, if not all, of the words in the text returned as misspelled. I tried debug50 with the small dictionary and cat text and found that the cursor in CHECK always returned NULL, so the strings were never compared. I can't figure out why it would be doing that. Here is my code for CHECK and, just in case the problem lies elsewhere, the code for LOAD. Thanks in advance for any help provided.

CHECK:

bool check(const char *word)
{
    //make word in lower case
    int strln = strlen(word + 1);
    char lower_word[strln];
    for (int i = 0; i < strln; i++)
    {
        lower_word[i] = tolower(word[i]);
    }

    // Hash the word to get its hash value
    int ht = hash(lower_word);
    node *cursor = table[ht];

    //important to compare case insensitive here!!!
    while (cursor != NULL)
    {
        if (strcasecmp(cursor->word, lower_word) == 0)
        {
            return true;
        }
        cursor = cursor->next;
    }

    return false;
}

LOAD:

bool load(const char *dictionary)
{
    //open dictionay file
    FILE *dict = fopen(dictionary, "r");
    //check for null
    if (dict == NULL)
    {
        printf("Could not open dictionary\n");
        return false;
    }
    //make a place to store read words
    char dw[LENGTH + 1];
    //read file
    while ((fscanf(dict, "%s", dw)) != EOF)
    {
        //allocate memory to list
        node *n = malloc(sizeof(node));
        if (n == NULL)
        {
            printf("malloc null\n");
            unload();
            return false;
        }
        //Use strcpy to copy each word into node
        strcpy(n->word, dw);
        n->next = NULL;

        //hash each word
        int ht = hash(n->word);
        node *head = table[ht];
        if (head == NULL)
        {
            table[ht] = n;
            printf("load %s\n", n->word);
        }
        else
        {
            n->next = table[ht];
            table[ht] = n;
        }
        s++;
    }
    fclose(dict);
    return true;
}
0

lower_word is not null terminated. Since it is being used as a string in strcasecmp that may (will?) cause unpredictable result.

0

I finally figured it out. It was because strlen was (word +1) and not (word) + 1. It's amazing what parentheses can do!

You must log in to answer this question.

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