C5050 Pset 5 speller Ошибка сегмента - PullRequest
0 голосов
/ 07 мая 2018

При запуске я получаю ошибку сегментации, и я был бы очень признателен за указатель на то, что я делаю неправильно.

Для тех, кто видит это вне тега cs50, я пытаюсь загрузить словарь (при загрузке), сравнить строку со словом из словаря (при проверке) и выгрузить словарь (при выгрузке).

Это то, что я написал до сих пор:

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

#include "dictionary.h"
#define HASH_MAX 27

/**
 * Returns true if word is in dictionary else false.
 */
typedef struct node
{
    char word[LENGTH + 1];
    struct node *next;
}
node;

node *hashtable[HASH_MAX];
int count = 0;


int hash(string word)
{
    int num = 0;
    for(int i = 0; word[i] != '\0'; i++)
    {
        num += word[i];
    }
    return num % HASH_MAX;
}

bool check(const char *word)
{
    char WordCopy[strlen(word) + 1];
    strcpy(WordCopy, word);

    for(int i = 0; i < strlen(WordCopy); i++)
    {
        tolower(WordCopy[i]);
    }

    node *cursor = hashtable[hash(WordCopy)];
    while(cursor != NULL)
    {
        if(strcmp(cursor -> word,WordCopy) == 0)
        {
            return true;
        }
        else
        {
            cursor = cursor -> next;
        }
    }
    return false;
}

/**
 * Loads dictionary into memory. Returns true if successful else false.
 */
bool load(const char *dictionary)
{
    node *head = hashtable[0];
    FILE *file = fopen(dictionary, "r");
    string word = NULL;
    node *new_node = malloc(sizeof(node));

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

    while(fscanf(file, "%s", word) != EOF)
    {
        if(new_node == NULL)
        {
            unload();
            return false;
        }
        else
        {
            strcpy(new_node -> word, word);

            new_node -> next = head;

            head = hashtable[hash(new_node -> word)];
        }
        fclose(file);

        count++;
        return true;
    }

    return true;
}

/**
 * Returns number of words in dictionary if loaded else 0 if not yet loaded.
 */
unsigned int size(void)
{
    return count;
}
/**
 * Unloads dictionary from memory. Returns true if successful else false.
 */
bool unload(void)
{
    node *head = hashtable[0];
    node *cursor = head;

    while(cursor != NULL)
    {
        node *temp = cursor;
        cursor = cursor -> next;
        free(temp);
    }
    return false;
}
...