cs50 pset5 定位内存时出现分段错误

问题描述 投票:0回答:0

卡在这里好几天了。加载 52209 字后,我一直遇到 Segmentation fault (core dumped)。我认为我在代码的某个地方不必要地消耗了内存,但我不确定在哪里。 我在加载函数的这一行得到了 Segmentation fault (core dumped) 错误

node *n = malloc(sizeof(node));

// Implements a dictionary's functionality

#include <ctype.h>
#include <stdbool.h>
#include <string.h>
#include <strings.h>
#include <stdio.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;

TODO: Choose number of buckets in hash table
const unsigned int N = 676;

// Hash table
node *table[N];

// word counter
int words = 0;

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

// Hashes word to a number
unsigned int hash(const char *word)
{
    // TODO: Improve this hash function
    if (strlen(word) == 1)
    {
        return toupper((word[0]) - 'A') * 26;
    }
    return toupper((word[0]) - 'A') * 26 + toupper(word[1]) - 'A';
}
bool isLoadedd = false;
// Loads dictionary into memory, returning true if successful, else false
bool load(const char *dictionary)
{
    char dicword[LENGTH + 1];
    FILE *dict = fopen(dictionary, "r");
    if(dict == NULL)
    {
        return false;
    }
    while(fscanf(dict,"%s", dicword) != EOF)
    {
        node *n = malloc(sizeof(node));
        if(n == NULL)
        {
            return false;
        }
        strcpy(n -> word, dicword);
        n -> next = table[hash(dicword)];
        table[hash(dicword)] = n;
        words++;
    };
    isLoadedd = true;
    return true;
}

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

void freee();
// Unloads dictionary from memory, returning true if successful, else false
bool unload(void)
{
    // TODO
    for(int i = 0 ; i < N ; i++)
    {
        freee(table[i]);
        if(table[0]== NULL && table[N-1]==NULL)
        {
            return true;
        }
    }
    return false;
}

void freee(node *n)
{
    if (n == NULL)
    {
        return;
    }
    freee(n->next);
    free(n);
}

我试图将 N 值更改为 26,但认为这可能会节省内存,但我遇到了同样的错误。

c hash malloc cs50 singly-linked-list
© www.soinside.com 2019 - 2024. All rights reserved.