首页 > 解决方案 > cs50 pset5 分段错误[使用哈希表在内存中加载文本]

问题描述

我目前正在处理来自 cs50 的 pset5

load我的整个程序编译成功,但在程序执行时调用的函数中间停止。

下面是我的load函数,你可以看到它给我一个segmentation fault错误的评论。

如果你能帮助我弄清楚我应该如何处理我的错误,请告诉我。
我知道这segmentation fault是程序尝试访问不属于它的内存时引起的。
但是,我已经分配了内存并检查了是否有足够的内存来继续程序。
我将提供注释以突出我的代码的作用。

// In another header file, I have defined 'LENGTH'
// Maximum length for a word
// (e.g., pneumonoultramicroscopicsilicovolcanoconiosis)
#define LENGTH 45

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

// Hash table
// I have initialized the array of `node` pointer to point `NULL`
node *table[N] = {NULL};

unsigned int word_counter = 0;

bool load(const char *dictionary)
{
    // Open file, and if cannot open, return false
    FILE *file = fopen(dictionary, "r");
    if (file == NULL)
    {
        return false;
    }

    // read string in the file into array of character, `word` until reaching end of the file 
    char word[LENGTH + 1];
    while (fscanf(file, "%s", word) != EOF)
    {
        // keep track of how many word exists in the file, for later use (not in this function)
        word_counter += 1;

        // allocated memory for struct type `node`, if not enough memory found, return false 
        node *n = (node*)malloc(sizeof(node));
        if (n == NULL)
        {
            return false;
        }

        // assign index by hashing (hash function will not be posted in this question though.)
        unsigned int index = hash(&word[0]);
        // copy the word from file, into word field of struct type `node`
        strncpy(n->word, word, sizeof(word));

        // Access the node pointer in this index from array(table), and check is its `next` field points to NULL or not. 
        // If it is pointing to NULL, that means there is no word stored in this index of the bucket
        if (table[index]->next == NULL)    // THIS IS WHERE PROGRAM GIVES 'segmentation fault' !!!! :(
        {
            table[index]->next = n;
        }
        else
        {
            n->next = table[index];
            table[index]->next = n;
        }
    }
    return true;
}

标签: ccs50

解决方案


您将 ant 初始化哈希表定义为:

node *table[N] = {NULL};

这意味着你有一个空指针数组。

当您在表中插入第一个值时,table[index](对于任何有效索引)将是一个空指针。这意味着table[index]->next尝试取消引用此空指针,您将有未定义的行为。

您需要先检查空指针:

if (table[index] == NULL)
{
    n->next = NULL;
}
else
{
    n->next = table[index];
}

table[index] = n;

推荐阅读