C 为什么我的代码链表不';t返回NULL和SEG故障

C 为什么我的代码链表不';t返回NULL和SEG故障,c,pointers,linked-list,null,segmentation-fault,C,Pointers,Linked List,Null,Segmentation Fault,我试图编码一个模式来复制,复制结构指针中的链表,但当我的最后一个元素是print时,这会导致seg故障,最后一个元素返回类型为0x0或0xF00000000000的地址。我没有发现我的代码中遗漏了什么,可能是当我复制结构中的int-dup(t_-child**ref,t_-child*src)链表时,但我对C的知识有限 下面我试着编写一个简单的代码来重现我的问题 #include <string.h> #include <stdio.h> #include <std

我试图编码一个模式来复制,复制结构指针中的
链表
,但当我的最后一个元素是print时,这会导致
seg故障
,最后一个元素返回类型为
0x0
0xF00000000000
的地址。我没有发现我的代码中遗漏了什么,可能是当我复制结构中的
int-dup(t_-child**ref,t_-child*src)
链表时,但我对
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);
}

嘿,你有没有检查你的链表是否以
NULL
结尾,或者甚至将第一个指针设置为
NULL

当您在链接列表中“移动”时,必须将NULL作为最后一个元素,然后在如下情况下:

while(*ptr_on_list* != NULL)
你不能挑剔。 因此,在到达
NULL
之前,请检查您是否停止了链接列表中的“移动”


希望我能帮助您,如果没有,请随时通知我。您忘记了将第一个节点的下一个指针设置为
null
。也没有在第一个节点中设置id。@AnttiHaapala很难找到我必须设置为
null
的位置,但我找到了它。thx@stark您所说的不要设置
id
是什么意思。我觉得不必设置它,只要在必要时传递arg
rank
。我错了?
while(*ptr_on_list* != NULL)