CS50 Speller с ошибками valgrind - PullRequest
0 голосов
/ 08 февраля 2019

Мой код компилируется и выполняет то, что я хочу, но valgrind продолжает выдавать ошибки, которые я не понимаю ни в малейшей степени.Это говорит о том, что я пытаюсь использовать неинициализированные переменные, но они очень четко инициализированы.Даже если я определяю переменную, она говорит, что она неинициализирована.

Ясно, что мой код работает, поэтому я не понимаю, какого черта в действительности заключается проблема.Я даже смотрел на решения других людей онлайн, и мой код, кажется, совпадает.valgrind просто ненавидит меня?Что происходит?

Мой код:

#include <ctype.h>
#include <stdbool.h>
#include <stdio.h>
#include <string.h>
#include <stdlib.h>

#include "dictionary.h"

// Represents number of buckets in a hash table
#define N 26

// Represents a node in a hash table
typedef struct node
{
    char word[LENGTH + 1];
    struct node *next;
}
node;

// Represents a hash table, AKA an array of nodes
node *hashtable[N];

// Number of Words loaded into memory
int wordnum = 0;

// Initialize custom functions to be defined later
unsigned int hash(const char *word);
bool load(const char *dictionary);
unsigned int size(void);
bool check(const char *word);
bool unload(void);

// Hashes word to a number between 0 and 25, inclusive, based on its first letter
unsigned int hash(const char *word)
{
    return tolower(word[0]) - 'a';
}

// Loads dictionary into memory, returning true if successful else false
bool load(const char *dictionary)
{
    // Open dictionary
    FILE *file = fopen(dictionary, "r");
    if (file == NULL)
    {
        unload();
        return false;
    }

    // Buffer for a word
    char word[LENGTH + 1];

    // Insert words into hash table
    while (fscanf(file, "%s", word) != EOF)
    {
        int index = hash(word) % N;
        if (hashtable[index] == NULL)
        {
            hashtable[index] = malloc(sizeof(node));
            for (int i = 0, n = strlen(word); i < n; i ++)
            {
                hashtable[index]->word[i] = word[i];
            }
            hashtable[index]->next = NULL;
            wordnum++;
        }
        else
        {
            node *new_node = malloc(sizeof(node));
            for (int i = 0, n = strlen(word); i < n; i ++)
            {
                new_node->word[i] = word[i];
            }
            new_node->next = hashtable[index];
            hashtable[index] = new_node;
            wordnum++;
        }
    }

    // Close dictionary
    fclose(file);

    // Indicate success
    return true;
}

// Returns number of words in dictionary if loaded else 0 if not yet loaded
unsigned int size(void)
{
    return wordnum;
}

// Returns true if word is in dictionary else false
bool check(const char *word)
{
    int index = hash(word);
    node *current = hashtable[index];
    while (current != NULL)
    {
        char tempword [LENGTH + 1];
        strcpy(tempword, word);
        for (int i = 0, n = strlen(tempword); i < n; i ++)
        {
            tempword[i] = tolower(tempword[i]);
        }
        if (strcmp(tempword, current->word) == 0)
        {
            return true;
        }
        current = current->next;
    }
    return false;
}

// Unloads dictionary from memory, returning true if successful else false
bool unload(void)
{
    for (int i = 0; i < N; i ++)
    {
        while (hashtable[i] != NULL)
        {
            node *buffer = hashtable[i];
            hashtable[i] = hashtable[i]->next;
            free(buffer);
        }
    }
    for (int i = 0; i < N; i ++)
    {
        if (hashtable[i] != NULL)
        {
            return false;
        }
    }
    return true;
}

1 Ответ

0 голосов
/ 08 февраля 2019

При загрузке вы инициализируете hashtable[index], когда находите слово для хранения там.При выгрузке вы пытаетесь освободить всех узлов хеш-таблицы.Что если в словаре нет слов, начинающихся с «z»?Тогда hashtable[25] не инициализируется и valgrind будет жаловаться.

Знаете ли вы, У CS50 есть стек-форум , который содержит множество вопросов и ответов для наборов CS50?

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...