【发布时间】:2020-09-05 11:16:36
【问题描述】:
我想散列小字典(“字典/小”)。主文件编译正确,但在运行时会产生 "Segmentation fault" 消息,函数为 insert()(特别是 malloc() 有问题,但我不知道是什么问题)。
哈希.c
#include <stdio.h>
#include <stdlib.h>
#include <stdbool.h>
#include <ctype.h>
#include <string.h>
typedef struct node
{
char* name;
struct node* next;
}
node;
node* first[26] = {NULL};
int hash(const char* buffer)
{
return tolower(buffer[0]) - 'a';
}
void insert(int key, const char* buffer)
{
node* newptr = malloc(sizeof(node));
if (newptr == NULL)
{
return;
}
strcpy(newptr->name, buffer);
newptr->next = NULL;
if (first[key] == NULL)
{
first[key] = newptr;
}
else
{
node* predptr = first[key];
while (true)
{
if (predptr->next == NULL)
{
predptr->next = newptr;
break;
}
predptr = predptr->next;
}
}
}
【问题讨论】:
-
strcpy(newptr->name, buffer);。name字段尚未初始化,因此未指向任何有效内存。malloc内存为name或将其更改为固定大小的数组。例如newptr->name = strdup(buffer)) -
但我用 malloc 为节点初始化内存(以及指向下一个节点的名称和指针)
-
你为 char 指针“name”分配了空间,而不是它应该指向的字符数组。
标签: c dictionary hash linked-list