【问题标题】:Why my code linked list don't return NULL and SEG FAULT instead为什么我的代码链表不返回 NULL 和 SEG FAULT
【发布时间】: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。我感觉不要设置它,只需在必要时传递 arg rank。我错了?

标签: c pointers linked-list null segmentation-fault


【解决方案1】:

您是否检查过您的链表是否以NULL 结尾,甚至是否将第一个指针设置为NULL

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

while(*ptr_on_list* != NULL)

您不能进行段错误。 因此,在到达NULL 之前,还要检查您是否停止在链接列表中“移动”。

希望对你有所帮助,如果没有,请随时关注我

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-11-29
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多