c - 尝试添加到 C 中链接列表末尾时出现段错误

标签 c list insert linked-list valgrind

我试图将一个节点添加到链接列表的末尾,但它触发了段错误,并且 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;
}

为了充分披露,我之前尝试发布这个问题,其中一位用户建议我需要修改我的代码以通过引用传递到我的函数中,而不是值,我认为我已经完成了,但我仍然遇到同样的错误。

谢谢!

最佳答案

问题是我按值传递给 init_list(),这导致我的列表的副本被初始化。

这随后导致 add_to_list 中的 while 循环无限循环,因为我的未初始化列表从未设置为 null。

解决方案由 rakib 提供.

关于c - 尝试添加到 C 中链接列表末尾时出现段错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25986368/

相关文章:

java - 删除排序列表中的相同项

mysql - INSERT 中的 SQL 子查询?

c# - 将字符串数组值插入 DataGridView C#

c++ - 从 2 unsigned int 中获取最小值

C++ 代码比它的 C 等效代码慢?

c - 让一个字符在数组中重复出现多次并计算得分。

javascript - 通过ajax在codeigniter中将数据库数据显示为列表

c - 函数调用后销毁

python - 以迭代方式计算成对列表的分数时遇到问题?

java - 将图像添加到 jar 中,使用 ANT 到特定位置