【问题标题】:Segfault when trying to add to end of linked list in C尝试添加到 C 中的链表末尾时出现段错误
【发布时间】: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-&gt;next != NULL) 行收到了 SIGSEGV-我不知道为什么那个循环不正确
  • 也许current-&gt;next 永远不会到达NULL。在声明fruit_list 时,请确保它已正确初始化。
  • 啊,没有通过引用我的列表初始化,谢谢!有没有办法让我把这个问题的答案归于你?
  • @user3773076 您可以自己编写答案,并将站点 rakib 作为解决方案的来源。

标签: c list insert linked-list valgrind


【解决方案1】:

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

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

解决方案由rakib提供。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-01-25
    • 1970-01-01
    • 2011-07-22
    • 1970-01-01
    • 2012-11-02
    • 2013-10-18
    相关资源
    最近更新 更多