C语言 为什么哈希函数给出分割错误?



我试图做一个拼写检查程序,我首先要把字典加载到内存中。为此,我尝试使用散列表。当我对哈希表使用哈希函数时,程序显示分段错误。

// Implements a dictionary's functionality
#include <stdbool.h>
#include <errno.h>
#include <stdio.h>
#include <string.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;
// Number of buckets in hash table
const unsigned int N = 6536;
// Hash table
node *table[N];
// Returns true if word is in dictionary, else false
bool check(const char *word)
{
//TODO
return false;
}
// Hashes word to a number
unsigned int hash(const char *word)         //Hashed using djb2
{
unsigned long hash = 5381; 
int c = 0;

while (c == *word++)
{
hash = ((hash << 5) + hash) + c; /* hash * 33 + c */
}
return hash;
}
// Loads dictionary into memory, returning true if successful, else false
bool load(const char *dictionary)
{
char *str = NULL;
FILE *dict = fopen(dictionary,"r");
node *temp = NULL;
if(dict == NULL)
{
//printf("Error: n", strerror(errno));
return false;
}
for(int i = 0; i < N; i++)
{
table[i] = NULL;
}
while(fscanf(dict, "%s", str) != 1)
{
unsigned int key = hash(str);
temp = malloc(sizeof(node));
if(temp == NULL)
{
return false;
}
if(table[key] != NULL)
{
temp->next = table[key]->next;
strcpy(temp->word, str);
table[key]->next = temp;
free(temp);
}
else
{
table[key] = malloc(sizeof(node));
table[key]->next = NULL;
strcpy(table[key]->word, str);
}
}
fclose(dict);
printf("SUCCESSn");
return true;
}

调试器显示seg。unsigned int key = hash(str);发生故障。我想知道如何解决这个问题。

Try

char str[MAX_LEN];

不是

char *str = NULL;

(在将MAX_LEN定义为适合您的应用程序之后)。

正如M Oehm在评论中指出的那样,我认为您可能也错误地解释了fscanf()的返回值。

最新更新