无限“信号11被丢弃".尝试添加到链接列表时与Valgrind循环 [英] Infinite "Signal 11 being dropped" loop with Valgrind while trying to add to linked list
问题描述
我试图在C语言中创建一个简单的单链接列表,并且在Valgrind中运行程序时遇到无限的"Singal 11正在被删除"循环.
I'm trying to create a simple singly linked list in C, and have encountered an infinite "Singal 11 being dropped" loop while running my program in 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
中的列表遍历,但是我不确定自己做错了什么.
I'm assuming the issue stems from my list traversal in add_to_list
, but I'm unsure about what I'm doing wrong.
谢谢!
推荐答案
您正在按值将结构传递给函数.这将在函数中创建该结构的副本,并且对该副本的更改将不会在调用函数中的结构上发生.
You're passing structs by value into functions. This will create a copy of the struct in the function, and changes to the copy will not occur on the struct in the calling function.
您应该在喜欢的c语言书中阅读有关指针的信息.
You should read about pointers in your favorite c-language book.
这篇关于无限“信号11被丢弃".尝试添加到链接列表时与Valgrind循环的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!