【发布时间】:2021-01-16 00:44:51
【问题描述】:
我尝试编写要复制的模式,在结构指针中复制 linked list,但是当我的最后一个元素是 print 时,会导致 seg fault 并且最后一个元素返回 0x0 或 @ 类型的地址987654324@。我没有找到我在代码中遗漏某些内容的地方,可能是当我在结构中复制 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: %i\n",m->child->id);
m->child = m->child->next;
printf("m->child %p\n", m->child);
if(m->child == NULL)
printf("m->child NULL\n");
}
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。 -
第一个节点也没有设置id。
-
@AnttiHaapala 很难找到必须设置为
NULL的位置,但我找到了。谢谢 -
@stark 你的意思是不要设置
id。我感觉不要设置它,只需在必要时传递 argrank。我错了?
标签: c pointers linked-list null segmentation-fault