CS50 Speller. c Выпуск - PullRequest
       9

CS50 Speller. c Выпуск

0 голосов
/ 28 мая 2020

У меня есть некоторые проблемы с задачей проверки орфографии CS50 в наборе задач 5. Для тех, кто не знаком с этой проблемой, моя программа в основном работает как проверка орфографии (вы вставляете словарь и текстовый файл, и программа возвращает все орфографические ошибки слова). Нашей задачей было написать пять функций (проверка, ha sh, загрузка, размер, выгрузка). Функция проверки проверяет, есть ли слово в заданном словаре. Ha sh в основном возвращает числовой индекс таблицы ha sh, которую я использовал для организации слов на основе ввода слова из текста. Функция загрузки в основном загружает все слова из файла словаря в таблицу ha sh. Функция размера возвращает размер словаря, и, наконец, функции выгрузки освобождают всю память, выделенную для моей программы. Однако, когда я тестирую свою программу с помощью check50, очевидно, возникает ошибка с освобождением памяти. Однако я не знаю, где может быть эта проблема?

Заранее спасибо!

 // Implements a dictionary's functionality

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

 #include "dictionary.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 = 26;

 // Hash table
 node *table[N];

 // Returns true if word is in dictionary else false
bool check(const char *word)
{
int x = hash(word);
for (node *temp = table[x]; temp != NULL; temp = temp->next)
{
    if (strcasecmp(word, temp->word) == 0)
    {
        return true;
    }
}
return false;

}

// Hashes word to a number
unsigned int hash(const char *word)
{
char s = word[0];

if(word[0] < 97)
{
    s = tolower(word[0]);
}
int index = s - 97;

return index;

}

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

if (file == NULL)
{
    printf("Could not open dictionary.\n");
    return false;
}

char theword[45];

while (fscanf(file, "%s", theword) != EOF)
{
    node *n = malloc(sizeof(node));

    if (n == NULL)
    {
        return false;
    }

    int wordlength = strlen(theword);

    int x = hash(theword);

    char tempword[45];

    if (table[x] == NULL)
    {
        for (int j = 0; j < wordlength; j++)
        {
            n->word[j] = theword[j];
        }

        n->next = NULL;

        table[x] = n;
    }

    for (node *temp = table[x]; temp != NULL; temp = temp->next)
    {
        node *temp2 = temp->next;

        if (temp2 == NULL)
        {
            for (int k = 0; k < strlen(theword); k++)
            {
                n->word[k] = theword[k];
            }
            temp->next = n;

            n->next = NULL;
        }
    }
}
return true;
}

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

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

    while (temp != NULL)
    {
        node *temp2 = temp->next;
        free(temp);
        temp = temp2;
    }
}
return true;
}

1 Ответ

0 голосов
/ 28 мая 2020

Утечка памяти вызвана тем, что указатель FILE не закрывается, но в вашем коде есть другая проблема, которая записывает данные за пределы области памяти. Ниже приводится сообщение об ошибке. Вот [ссылка] для отладки и воспроизведения этой ошибки.

  Memory access warning: memory spaces are not freed; continue execution.
  # 1 memory space is allocated at
  #    file:/musl-1.1.10/src/stdio/__fdopen.c::20, 10
  # total 1164 bytes
  #

  Memory access error: writing to the outside of a memory space; abort execution.
  # Writing 1 bytes to 0xffefc609 will clobber other memory-spaces.
  #
  # The memory-space-to-be-written (start:0xffefc5dc, size:45 bytes) is bound to 'theword' at
  #    file:/dictionary.c::57, 8
  #
  #  0xffefc5dc               0xffefc608
  #  +------------------------------+
  #  |the memory-space-to-be-written|......
  #  +------------------------------+
  #                                  ^~~~~~~~~~
  #        the write starts at 0xffefc609 that is right after the memory-space end.
  #
  # Stack trace (most recent call first) of the write.
  # [0]  file:/musl-1.1.10/src/stdio/vfscanf.c::271, 12
  # [1]  file:/musl-1.1.10/src/stdio/fscanf.c::28, 8
  # [2]  file:/dictionary.c::59, 10
  # [3]  file:/speller.c::40, 19
  # [4]  [libc-start-main]
Segmentation fault
...