【发布时间】:2014-08-16 12:04:04
【问题描述】:
我正在尝试创建程序,您可以在其中输入“+word”并添加单词,当您输入“-word”时,它会将单词从链接列表中取出。
插入单词对我来说很好,但删除它会导致分段错误。我不确定问题出在哪里。另外,有没有办法可以提示分段错误在哪里?
void
remove_from_list(struct linked_list *list, char *data)
{
struct node *current_node = list->head;
struct node *previous_node = NULL;
while (current_node != NULL) {
if (current_node->data == data) {
break;
}
previous_node = current_node;
current_node = current_node->next;
}
if (previous_node == NULL) {
list->head = list->head->next;
} else {
previous_node->next = current_node->next;
}
free(current_node);
if (list->tail == current_node)
list->tail = previous_node;
}
int
main(void)
{
struct linked_list list = { .head = NULL, .tail = NULL };
char word[50];
do {
printf("Enter string: ");
fgets(word, 50, stdin);
if (word[0] == '+')
add_to_list(&list, word);
else if (word[0] == '-')
remove_from_list(&list, word);
} while (word[0] != '\n');
print_list_rec(&list);
free_list(&list);
return 0;
}
【问题讨论】:
-
您应该使用实际的字符串比较(如
strncmp)来查找节点是否包含您的字符串。这一切:current_node->data == data所做的只是比较指针。 -
因为字符串在 C 中很棘手,如果仅从内存管理的角度来看,也许可以尝试使用相同的代码,但使用整数作为
data,看看是否遇到相同的问题。 -
关于这一行:free_list(&list);,你不能释放堆栈上的结构。但是,您可以遍历链表,释放链表中的每个节点(第一个节点除外,因为它在堆栈上。
-
函数 remove_from_list() 不能正确处理空列表,而是尝试 'list->head = list->head->next;'它正在获取地址 0 (null) 之后的偏移地址。
-
关于这一行:struct linked_list list = { .head = NULL, .tail = NULL };不清除 .next 字段或 .data 字段。更好的一行是:struct linked_list list = { 0 };
标签: c linked-list segmentation-fault singly-linked-list