jca*_*eup 2 c load segmentation-fault strcpy strncpy
我有这个函数"加载",我从字典中读取单词并将它们放在链表的哈希表中.当我尝试读取一行并将其保存在我的new_node-> text中时,编译器返回SEGMENTATION FAULT,我不知道为什么.当我使用strncpy时,错误会出现.
#define HASHTABLE_SIZE 76801
typedef struct node
{
char text[LENGTH+1];
//char* text;
//link to the next word
struct node* next_word;
}
node;
node* hashtable[HASHTABLE_SIZE];
bool load(const char* dictionary)
{
FILE* file = fopen(dictionary,"r");
unsigned long index = 0;
char str[LENGTH+1];
if(file == NULL)
{
printf("Error opening file!");
return false;
}
while(! feof(file))
{
node * new_node = malloc(sizeof(node)+1000);
while( fscanf(file,"%s",str) > 0)
{
printf("The word is %s",str);
strncpy(new_node->text,str,LENGTH+1);
//strcpy(new_node->text,str);
new_node->next_word = NULL;
index = hash( (unsigned char*)new_node->text);
if(hashtable[index] == NULL)
{
hashtable[index] = new_node;
}
else
{
new_node->next_word = hashtable[index];
hashtable[index] = new_node;
}
n_words++;
}
//free(new_node);
}
fclose(file);
loaded = true;
return true;
}
Run Code Online (Sandbox Code Playgroud)
让我们逐行看看你的代码,好吗?
while(! feof(file))
{
Run Code Online (Sandbox Code Playgroud)
这不是正确的使用方法feof- 查看帖子为什么"while(!feof(file))"总是错的?就在StackOverflow上.
node * new_node = malloc(sizeof(node)+1000);
Run Code Online (Sandbox Code Playgroud)
嗯..好.我们为一个节点和1000个字节分配空间.这有点奇怪,但是嘿......内存很便宜.
while( fscanf(file,"%s",str) > 0)
{
Run Code Online (Sandbox Code Playgroud)
嗯...... 另一个循环?好...
printf("The word is %s",str);
strncpy(new_node->text,str,LENGTH+1);
//strcpy(new_node->text,str);
new_node->next_word = NULL;
index = hash( (unsigned char*)new_node->text);
Run Code Online (Sandbox Code Playgroud)
嘿! 等一下......在第二个循环中,我们new_node反复覆盖......
if(hashtable[index] == NULL)
{
hashtable[index] = new_node;
}
else
{
new_node->next_word = hashtable[index];
hashtable[index] = new_node;
}
Run Code Online (Sandbox Code Playgroud)
假设两个单词都散列到同一个桶:
好的,所以第一次通过循环,hashtable[index]将指向NULL并设置为指向new_node.
通过循环的第二次,hashtable[index]是不是NULL因此new_node将作出指向任何hashtable[index]点(提示:new_node)和hashtable[index]将变为指向new_node).
你知道ouroboros是什么吗?
现在假设他们没有哈希到同一个桶:
其中一个桶现在包含错误的信息.如果先在桶1中添加"hello",先在桶2中添加"goodbye",当您尝试遍历桶1时,可能(仅因为链接代码被破坏)找到不再属于桶1的"再见"所有.
您应该为要添加的每个单词分配一个新节点.不要重复使用相同的节点.