C:打印单链表分割错误

问题描述 投票:0回答:2

有人可以解释为什么我会产生分段错误:11在主函数中调用display_list(head)吗?当我使用NULL初始化列表(头)时,我没有遇到分段错误,但是我不明白为什么需要这样做,或者在这种情况下这是最佳实践。抱歉,代码混乱,我是C的新手!

#include <stdio.h>
#include <stdlib.h> 
#define NEWLINE printf("\n");


struct le {

    int value;
    struct le * next;

};

typedef struct le listelement; 

typedef listelement * list; 



void insert(int v, list * l) {

    listelement * new; 
    new = malloc(sizeof(listelement)); 
    new->value = v; 
    new->next = *l; 
    *l = new; 

}

void display_list(list l) {

    if (l == NULL) printf("leer\n");
    else
    {
            while (l != NULL) {
                printf("%d ", l->value);
                l = l->next;
            }
            NEWLINE;
    }
}


int main() {

    list head; 

    int i;

    for (i = 1; i <= 3; i++)
    {
        insert(i, &head);
    }

    display_list(head);

    return 0;

}

c singly-linked-list
2个回答
0
投票
  Memory access error: dereferencing an uninitialized pointer; abort execution.
  # Reading 4 bytes from a random address (0x8199f38).
  #
  # Stack trace (most recent call first) of the read.
  # [0]  file:/prog.c::35, 17
  # [1]  file:/prog.c::54, 5
  # [2]  [libc-start-main]

这里是link,用于调试此段错误。只需单击“运行”。


0
投票

此行试图将结构复制到未定义的内存位置

new->next = *l; 

您的new刚刚被分配,它的next成员值具有任意地址,并且上一行试图在其中复制l所指向的结构的内容。

您是不是要这样做?

new->next = l;
© www.soinside.com 2019 - 2024. All rights reserved.