简体   繁体   English

为什么我的代码链表不返回 NULL 和 SEG FAULT

[英]Why my code linked list don't return NULL and SEG FAULT instead

I try to code a pattern to copy, duplicate a linked list in a struct pointer, but when my last element is print that is cause a seg fault and the last element return an address of type 0x0 or 0xF00000000000 .我尝试编写一个模式来复制、复制结构指针中的linked list ,但是当我的最后一个元素被打印时会导致seg fault并且最后一个元素返回类型为0x00xF00000000000的地址。 I don't find where I miss something in my code, may be when I duplicate int dup(t_child **ref, t_child *src) the linked list in my struct, but my knowledge in the C is limited.我没有找到我在代码中遗漏了什么地方,可能是当我在结构中复制int dup(t_child **ref, t_child *src) linked list ,但我在C方面的知识有限。

below I try to make a simple code to reproduce my problem.下面我尝试制作一个简单的代码来重现我的问题。

#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);
}

terminal output终端输出

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

Hey did you check that your linked list ended with NULL or even setting the first pointer with NULL ?嘿,您是否检查过您的链表是否以NULL结尾,甚至是否将第一个指针设置为NULL

When you "move" inside your linked list you must have NULL as last element, then in case like :当您在链表中“移动”时,您必须将 NULL 作为最后一个元素,然后在以下情况下:

while(*ptr_on_list* != NULL)

you can't segfault.你不能段错误。 So also check you stop "moving" in your linked list BEFORE you reach the NULL .因此,在您到达NULL之前,还要检查您是否在链接列表中停止“移动”。

Hope i helped you, feel free to notice me if not希望我帮到你,如果没有,请随时注意我

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM