c - C中字母链表中的分段错误
问题描述
我的字母链表中出现分段错误,我将其固定到最后一个 else 语句中的 prev。
else
{
prev->next = new_node;
new_node->next = ptr;
return 0;
}
我该如何解决这个问题?
int add(char *str, char *file) {
struct word_node *new_node = malloc(sizeof(struct word_node));
unsigned len = strlen(str) + 1;
char *s = malloc(len);
memcpy(s, str, len);
new_node->data = s;
new_node->count = 1;
new_node->filename = file;
new_node->next = NULL;
// struct word_node
if (head == NULL)
{
head = new_node;
return 0;
}
struct word_node* ptr = head;
struct word_node* prev = NULL;
while (ptr != NULL)
{
if (strcmp(ptr->data, new_node->data) > 0)
{
break;
}
ptr = ptr->next;
}
if (ptr == head)
{
new_node->next = head;
head = new_node;
return 0;
}
else
{
prev->next = new_node;
new_node->next = ptr;
return 0;
}
}
解决方案
您的代码简化为:
struct word_node* prev = NULL;
prev->next = new_node;
现在看到问题了吗?
要运行第二行,您必须prev
在使用之前将其初始化为有效的值。
推荐阅读
- android - android - recyclerview - 获取位图
- loadrunner - 如何在 vugen/load runner 中捕获/记录评级(星)
- python - 父类方法被称为鄙视子类的声明
- html - 将水平数据列表转换为垂直媒体查询,CSS
- eclipse - SAP Hana - 尝试通过 Eclipse 导入数据时出错
- jquery - jQ根据周围的div动态设置div的高度
- java - 等到检索到 Firestore 数据以启动活动
- java - 在 Android Studio 中,我所有的图标都是模糊的,我不知道为什么
- gtk3 - Glade,pygobject - 关闭和打开一个窗口 - Gtk-CRITICAL 错误和崩溃
- php - 路线停止工作