c语言 - 为什么我的代码链表不返回 NULL 和 SEG 错误



我试图编写一个模式来复制,在结构指针中复制linked list,但当我的最后一个元素被打印时,会导致seg fault和最后一个元件返回类型为0x00xF00000000000的地址。我没有发现我在代码中遗漏了什么,可能是当我在结构中复制int dup(t_child **ref, t_child *src)linked list时,但我在C中的知识是有限的。

下面我尝试制作一个简单的代码来重现我的问题。

#include <string.h>
#include <stdio.h>
#include <stdlib.h>
typedef struct s_child t_child;
struct s_child {
int id;
t_child *next;
};
typedef struct s_mother t_mother;
struct s_mother {
t_child *child;
t_mother *next;
};
int add_child(t_child **ref, int rank) {
t_child *temp;
temp = NULL;
if(!(temp = (t_child*)malloc(sizeof(t_child))))
return (0);
temp->id = rank;
temp->next = (*ref);
(*ref) = temp;
return(1);
}
int dup(t_child **ref, t_child *src) {
int rank = 0;
int ret = 0;
while(src) {
ret = add_child(ref, rank);
if(!ret)
break;
rank++;
src = src->next;
}
return(ret);
}
int add_mother(t_mother **ref, t_child *c) {
t_mother *temp;
temp = NULL;
if(!(temp = (t_mother*)malloc(sizeof(t_mother))))
return (0);
dup(&temp->child, c);
temp->next = (*ref);
(*ref) = temp;
return(1);
}
int main() {
t_child *c;
c = NULL;
for(int i = 0 ; i < 4 ; i++) {
add_child(&c, i);
}
t_mother *m;
m = NULL;
add_mother(&m, c);
while(m->child) {
printf("id: %in",m->child->id);
m->child = m->child->next;
printf("m->child %pn", m->child);
if(m->child == NULL) 
printf("m->child NULLn");
}
return(0);
}

终端输出

id: 3
m->child 0x7fb302402b60
id: 2
m->child 0x7fb302402b50
id: 1
m->child 0x7fb302402b40
id: 0
m->child 0xf000000000000000
[1]    16550 segmentation fault  ./a.out

嘿,你检查过你的链表是否以NULL结尾,或者是否用NULL设置了第一个指针?

当你";移动";在您的链接列表中,您必须将NULL作为最后一个元素,然后在类似的情况下

while(*ptr_on_list* != NULL)

你不能插科打诨。所以也要检查你是否停止";移动";在您到达NULL之前,在您的链接列表中。

希望我帮了你,如果不是,请随时注意我

最新更新