【发布时间】:2014-09-23 03:26:34
【问题描述】:
我正在尝试将一个节点添加到我的链表的末尾,但它会触发一个段错误,并且 valgrind 的进一步检查显示一个无限的“信号 11 从线程 0 丢弃”循环。
我的 .h 文件:
#ifndef TEST_H
#define TEST_H
struct fruit {
char name[20];
};
struct node {
struct fruit * data;
struct node * next;
};
struct list {
struct node * header;
unsigned count;
};
#endif
我的 .c 文件:
#include "test.h"
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
void init_list(struct list my_list)
{
my_list.header = NULL;
my_list.count = 0;
}
void add_to_list(struct list * my_list, struct node * fruit_node)
{
struct node * current; /* node to traverse list */
if(my_list -> header -> next == NULL) { /* check if no other nodes have been inserted, if so, insert at head */
my_list -> header -> next = fruit_node;
} else {
current = my_list -> header; /* start at header */
while(current->next != NULL) { /* loop will terminate once end of list is encountered */
current = current -> next;
}
current = fruit_node; /* add node */
}
}
int main()
{
struct fruit fruit_array[5];
struct list fruit_list;
struct node * my_node;
strcpy(fruit_array[0].name, "Apple");
strcpy(fruit_array[1].name, "Mango");
strcpy(fruit_array[2].name, "Banana");
strcpy(fruit_array[3].name, "Pear");
strcpy(fruit_array[4].name, "Orange");
init_list(fruit_list);
my_node = malloc(sizeof(struct node));
my_node -> data = &fruit_array[0];
my_node -> next = NULL;
add_to_list(&fruit_list, my_node);
return 0;
}
为了全面披露,我之前尝试过发布这个问题,其中用户建议我需要修改我的代码以通过引用而不是值传递到我的函数中,我认为我已经完成了,但我仍然遇到同样的错误。
谢谢!
【问题讨论】:
-
使用
gdb并找出你得到段错误的确切位置,这将有助于找出它发生的原因。 -
gdb 说在
while(current->next != NULL)行收到了 SIGSEGV-我不知道为什么那个循环不正确 -
也许
current->next永远不会到达NULL。在声明fruit_list 时,请确保它已正确初始化。 -
啊,没有通过引用我的列表初始化,谢谢!有没有办法让我把这个问题的答案归于你?
-
@user3773076 您可以自己编写答案,并将站点 rakib 作为解决方案的来源。
标签: c list insert linked-list valgrind