尝试添加到链表时,无限“信号11被丢弃”循环与Valgrind

时间:2014-09-23 01:44:20

标签: c linked-list valgrind

我试图在C中创建一个简单的单链表,并遇到了一个无限的" Singal 11被丢弃"在Valgrind中运行我的程序时循环。

我的.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 <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 fruit my_fruit)
{
    struct node my_node;
    struct node nav_node;

    my_node.data = &my_fruit;
    my_node.next = NULL;

    if(my_list.count == 0) {    /* set head node if list is empty */
        my_list.header = &my_node;
        my_list.count++;
    } else {
        nav_node = *my_list.header;

        while (nav_node.next != NULL) { /* traverse list until end */
            nav_node = *nav_node.next;
        }

        nav_node.next = &my_node;

        my_list.count++;
    }

}

int main()
{
    struct fruit fruit_array[5];
    struct list fruit_list;
    int i;

    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);

    for(i=0; i < 5; i++) {
        add_to_list(fruit_list, fruit_array[i]);
    }

    return 0;
}

我假设问题源于add_to_list中的列表遍历,但我不确定我做错了什么。

谢谢!

1 个答案:

答案 0 :(得分:1)

您将值通过结构传递给函数。这将在函数中创建结构的副本,并且对调用函数中的结构不会发生对副本的更改。

你应该阅读你最喜欢的c语言书中的指针。