c - 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;
}
解决方案
您将 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;
推荐阅读
- rust - 如何使用运算符“?” 与共享 mpsc?
- windows - 上下文切换的时间
- google-apps-script - 同时来自多个用户的 appendRow() 和 deleteRow()
- spring - Spring Boot 应用程序无法启动异常 org.springframework.beans.factory.NoSuchBeanDefinitionException:
- javascript - 如何播放保存在我的谷歌驱动器上的视频文件?
- c++ - 如何防止检测到堆栈粉碎?
- javascript - 我希望我的代码在页面加载但 onload 不起作用时运行
- javascript - Javascript+HTA,重新加载 iframe 并保持滚动位置
- go - 无法捕捉细节
- javascript - React js如何从firebase的snapshot.val()中提取数据