我需要编写在哈希表中加载字典的函数。我对错误消息感到困惑:c:37:20运行时错误:加载了'const char'类型的空指针,该错误在分段错误中运行。>
我试图更改加载功能,但仍然没有帮助。并尝试为哈希表分配内存,因为我认为问题可能出在内存泄漏中。
` // Represents number of buckets in a hash table
#define N 26
// Represents a node in a hash table
typedef struct node
{
char word[LENGTH + 1];
struct node *next;
}
node;
// Represents a hash table
node *hashtable[N];
// Hashes word to a number between 0 and 25, inclusive, based on its first letter
unsigned int hash(const char *word)
{
// Allocates memory for hashtable
int *ht = malloc(26*sizeof(int));
if(!ht)
{
unload();
return false;
}
return tolower(word[0]) - 'a'; // this is error line 37:20
}
// Loads dictionary into memory, returning true if successful else false
bool load(const char *dictionary)
{
// Initialize hash table
for (int i = 0; i < N; i++)
{
hashtable[i] = NULL;
}
// Open dictionary
FILE *file = fopen(dictionary, "r");
if (file == NULL)
{
unload();
return false;
}
// Buffer for a word
char word[LENGTH + 1];
// Insert words into hash table
while (fscanf(file, "%s", word) != EOF)
{
for (int i = 0; i < N; i++ )
{
// Allocate memory for node for each new word
node *new_node = malloc(sizeof(node));
if (!new_node)
{
unload();
return false;
}
// Copies word into node
strcpy(new_node->word, word);
new_node->next = NULL;
// Hashes word
hash(new_node->word);
// Inserts word into linked list
if(hashtable[i] == 0)
{
hashtable[i] = new_node;
}
else if(hashtable[i] == new_node)
{
new_node->next = hashtable[i];
hashtable[i] = new_node;
}
}
}
// Close dictionary
fclose(file);
// Indicate success
return true;
}
加载字典时,函数load应该重新调整为true。但是我遇到了分割错误。这是否意味着我没有从加载功能获得正确的输出?
答案 0 :(得分:1)
在
new_node->next = NULL; hash(new_node->word); // Inserts word into linked list if(hashtable[i] == 0) { hashtable[i] = new_node; } else if(hashtable[i] == new_node) { new_node->next = hashtable[i]; hashtable[i] = new_node; }
您不使用 hash()的结果,而是使用 i 而不是哈希结果作为 hashtable 中的索引,如果< em> N 大于26,您从 hashtable 中读取/写入,在其他情况下,您没有将单词放在正确的条目中,因为第一个在索引0处,第二个在索引处1等等,不管他们的第一个字母
请注意,else if(hashtable[i] == new_node)
永远是不正确的,实际上是永远不会到达的,因为if(hashtable[i] == 0)
永远都是正确的,因为您限制了要阅读的单词数
必须做些类似的事情
int h = hash(new_node->word);
// Inserts word into linked list
if(hashtable[h] == 0)
{
hashtable[h] = new_node;
new_node->next = NULL;
}
else
{
new_node->next = hashtable[h];
hashtable[h] = new_node;
}
但实际上可以简化为:
int h = hash(new_node->word);
new_node->next = hashtable[h];
hashtable[h] = new_node;
请注意,我想您不会多次读取同一单词(这是一本字典)
要做
while (fscanf(file, "%s", word) != EOF)
之所以危险,是因为如果所读单词的长度超过LENGTH,则没有保护措施
假设 LENGTH 为32 do(单词可以存储32个字符,最后一个空字符也可以):
while (fscanf(file, "%32s", word) == 1)
没有理由进行循环:
for (int i = 0; i < N; i++ ) { ... }
删除它(当然不是它的主体),所以:
while (fscanf(file, "%32s", word) == 1)
{
// Allocate memory for node for each new word
node *new_node = malloc(sizeof(node));
if (!new_node)
{
unload();
return false;
}
// Copies word into node
strcpy(new_node->word, word);
int h = hash(new_node->word);
new_node->next = hashtable[h];
hashtable[h] = new_node;
}
tte part
// Initialize hash table
for (int i = 0; i < N; i++)
{
hashtable[i] = NULL;
}
是无用的,因为全局的 hashtable 初始化为0
如果您想重新加载字典,则需要先释放链表,然后再重置为NULL
内存泄漏
hash 中的 malloc 是无用的,只会造成内存泄漏,将其删除:
// Hashes word to a number between 0 and 25, inclusive, based on its first letter
unsigned int hash(const char *word)
{
return tolower(word[0]) - 'a';
}
警告如果首字母不是a-z或A-Z,则返回索引不是 hashtable
的有效索引出于可读性原因,将#define N 26
替换为#define N ('z' - 'a' + 1)
添加缺失定义的提案:
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <ctype.h>
#define bool int
#define true 1
#define false 0
// Represents number of buckets in a hash table
#define N ('z' - 'a' + 1)
// Represent max word length
#define LENGTH 32
// Represents a node in a hash table
typedef struct node
{
char word[LENGTH + 1];
struct node * next;
}
node;
// Represents a hash table
node * hashtable[N];
// Hashes word to a number between 0 and 25, inclusive, based on its first letter
unsigned int hash(const char *word)
{
return tolower(word[0]) - 'a';
}
// probable goal : empty hashtable
void unload()
{
for (size_t i = 0; i != N; ++i) {
while (hashtable[i] != NULL) {
node * next = hashtable[i]->next;
free(hashtable[i]);
hashtable[i] = next;
}
}
}
// Loads dictionary into memory, returning true if successful else false
bool load(const char *dictionary)
{
// Open dictionary
FILE * file = fopen(dictionary, "r");
if (file == NULL)
return false;
// Buffer for a word
char word[LENGTH + 1];
// Insert words into hash table
while (fscanf(file, "%32s", word) == 1)
{
if (isalpha(word[0])) {
// Allocate memory for node for each new word
node * new_node = malloc(sizeof(node));
if (!new_node)
{
unload();
return false;
}
// Copies word into node
strcpy(new_node->word, word);
int h = hash(new_node->word);
new_node->next = hashtable[h];
hashtable[h] = new_node;
}
}
// Close dictionary
fclose(file);
// Indicate success
return true;
}
int main(int argc, char ** argv)
{
if (argc != 2)
printf("Usage : %s <dictionary>\n", *argv);
else if (!load(argv[1]))
fprintf(stderr, "Error when loading '%s'\n", argv[1]);
else {
puts("dictionary content");
for (size_t i = 0; i != N; ++i) {
node * n = hashtable[i];
if (n != NULL) {
printf("%c :", i + 'a');
do {
printf(" %s", n->word);
n = n->next;
} while (n != NULL);
putchar('\n');
}
}
unload();
}
}
编译和执行:
pi@raspberrypi:/tmp $ gcc -pedantic -Wextra -Wall d.c
pi@raspberrypi:/tmp $ cat d
alternate
bellow and
Below
dictionary
Hash main zombie
test
Zorro
pi@raspberrypi:/tmp $ ./a.out
Usage : ./a.out <dictionary>
pi@raspberrypi:/tmp $ ./a.out d
dictionary content
a : and alternate
b : Below bellow
d : dictionary
h : Hash
m : main
t : test
z : Zorro zombie
在 valgrind 下执行:
pi@raspberrypi:/tmp $ valgrind ./a.out d
==2370== Memcheck, a memory error detector
==2370== Copyright (C) 2002-2017, and GNU GPL'd, by Julian Seward et al.
==2370== Using Valgrind-3.13.0 and LibVEX; rerun with -h for copyright info
==2370== Command: ./a.out d
==2370==
dictionary content
a : and alternate
b : Below bellow
d : dictionary
h : Hash
m : main
t : test
z : Zorro zombie
==2370==
==2370== HEAP SUMMARY:
==2370== in use at exit: 0 bytes in 0 blocks
==2370== total heap usage: 13 allocs, 13 frees, 5,872 bytes allocated
==2370==
==2370== All heap blocks were freed -- no leaks are possible
==2370==
==2370== For counts of detected and suppressed errors, rerun with: -v
==2370== ERROR SUMMARY: 0 errors from 0 contexts (suppressed: 6 from 3)