简体   繁体   中英

CS50 pset5 Speller [2021] - " :( program is free of memory errors"

I get error ":( program is free of memory errors valgrind tests failed; see log for more information."

Here is my code:


    // Implements a dictionary's functionality
    
    #include <stdbool.h>
    #include <stdio.h>
    #include "dictionary.h"
    #include <ctype.h>
    #include <stdlib.h>
    #include <string.h>
    #include <strings.h>
    
    // Represents a node in a hash table
    typedef struct node
    {
        char word[LENGTH + 1];
        struct node *next;
    }
    node;
    
    // Number of buckets in hash table
    const unsigned int N = 27;
    
    // Hash table
    node *table[N];
    
    int size_n = 0;
    
    
    ```// Returns true if word is in dictionary, else false
    bool check(const char *word)
    {
        //Hash Number
        unsigned int number;
        number = hash(word);
    
        node *n;
    
        n = table[number];
    
        //Check for the word in the linked-list inside the Hash table
        while (n->next != NULL)
        {
            if (strcasecmp(n->word, word) == 0)
            {
                return true;
            }
    
            n = n->next;
        }
    
        //Return false if word not found in Hash table
        return false;
    }
    
    // Hashes word to a number
    unsigned int hash(const char *word)
    {
        unsigned int number = 0;
    
        //If word starts with '
    
        if (word[0] == 44)
        {
            number = 0;
        }
    
        //Assign Hash number alphbetically
    
        else if (toupper(word[0]) >=65 && toupper(word[0])<=90)
        {
            number = (toupper(word[0]) - 64);
        }
    
        return number;
    }
    
    // Loads dictionary into memory, returning true if successful, else false
    bool load(const char *dictionary)
    {
        //Open dictionary
        FILE *F = fopen(dictionary, "r");
    
        //Check if file is opened
        if (F == NULL)
        {
        return false;
        }
    
        //Temporary string to store words
        char temp[LENGTH + 1];
    
        unsigned int number;
    
        //Initialize linked-list pointers to NULL so that last element of every linked-list points to NULL
        node *p = malloc(sizeof(node));
        for (int i = 0; i < N; i++)
        {
            p->next = NULL;
            table[i] = p;
        }
    
        //Loads the dictionary in the Hash Table
        while(fscanf(F, "%s", temp) != EOF)
        {
            printf("%s", temp);
            number = hash(temp);
    
            //Allocate memory for the dictionary word
            node *n = malloc(sizeof(node));
    
            if (n == NULL)
            {
                return false;
            }
    
            //Store dictionary word in the node
            strcpy(n->word,  temp);
    
            //Insert the node between head and first element of linked-list
            n->next = table[number];
            table[number] = n;
    
            //Counts the number of words of the dictionary stored in the memory
            size_n++;
        }
    
        free(p);
        fclose(F);
        return true;
    }
    
    // Returns number of words in dictionary if loaded, else 0 if not yet loaded
    unsigned int size(void)
    {
        return size_n;
    }
    
    
    // Unloads dictionary from memory, returning true if successful, else false
    bool unload(void)
    {
        //Iterates over each head of the Hash table
        for (int i = 0; i < N; i++)
        {
            node *temp = NULL;
            node *dlt = NULL;
    
            temp = table[i];
    
            while (temp->next != NULL)
            {
                dlt = temp;
                temp = temp->next;
                free(dlt);
            }
        }
        return true;
    }

Here are the errors in valgrind check50:

Cause valgrind tests failed; see log for more information. Log


    running valgrind --show-leak-kinds=all --xml=yes --xml-file=/tmp/tmplj9r16i7 -- ./speller substring/dict substring/text...
    checking for output "MISSPELLED WORDS\n\nca\ncats\ncaterpill\ncaterpillars\n\nWORDS MISSPELLED: 4\nWORDS IN DICTIONARY: 2\nWORDS IN TEXT: 6\n"...
    checking that program exited with status 0...
    checking for valgrind errors...
    Invalid read of size 8: (file: dictionary.c, line: 40)
    Invalid read of size 8: (file: dictionary.c, line: 149)

I cannot find other way to solve this. And I get errors if I do it this way.

The valgrind errors are not obvious to me. What am I doing wrong?

This is wrong

//Initialize linked-list pointers to NULL so that last element of every linked-list points to NULL node *p = malloc(sizeof(node)); for (int i = 0; i < N; i++) { p->next = NULL; table[i] = p; }

You're not initialising the linked list pointers to NULL, you're initialising them to p and then you call free on p at the end of load. This leaves every single linked list in an invalid state, as the head pointer is left pointing to memory you no longer own.

table[i] = NULL;

Would have been correct, though still unnecessary as table is a global variable and thus default initialises to zero.

This part in check is also incorrect, as has already been pointed out.

while (n->next != NULL)

It is always wrong to check if next is NULL. We don't care if next is NULL, we only care if n is NULL.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM