0
링크 된 목록의 끝 부분에 노드를 추가하려고하지만 segfault가 트리거되고 valgrind에서 추가 검사가 무한 "Signal 11 스레드 0 "루프.Segfault가 C에서 연결된 목록의 끝에 추가하려고하는 경우
내 .H 파일 :
내 .c 파일#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
: 전체 공개에 대한
#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'를 사용하여 segfault를 얻는 곳을 정확히 찾아 내면 왜 일어나는지 알 수 있습니다. –
gdb는 SIGSEGV가'while (current-> next! = NULL)'에서 수신했다고 말합니다. - 왜 그 루프가 부정확 한지는 모르겠지만 –
아마도'current-> next'는 결코'NULL'에 도달하지 못할 것입니다. fruit_list를 선언하는 동안 제대로 초기화되었는지 확인하십시오. –