简单链表中的分段错误?

Segmentation fault in a simple linked list?

我正在尝试实现一个简单的链表。当我尝试编译时,它没有显示任何错误。但是当 运行 它时,它给出了分段错误。我分析了代码,但我找不到任何错误,可能是我这边的错误,我不知道。 请帮我找出代码中的错误。 预先感谢所有建议

#include<stdio.h>
#include<stdlib.h>

struct node{
  int data;
  struct node* next;
};
void push(struct node** first, int data){

  struct node* new_node;
  new_node =(struct node*)malloc(sizeof(struct node));

  /*printf("Enter the data\n");
  scanf("%d",&new_node->data);*/
  new_node->data = data;
  new_node->next= NULL;

  if(*first==NULL){
    *first = new_node;
    return;
  }
  new_node->next= *first;
  *first = new_node;
}

void insert_node(struct node* prv, int data){

  if(prv==NULL){
    printf("previous node cannot be null\n");
    return;
  }

  struct node* new_node;
  new_node = (struct node*)malloc(sizeof(struct node));

/*  printf("Enter the data\n");
  scanf("%d",&new_node->data); */
  new_node->data = data;
  new_node->next = prv->next;
  prv->next = new_node;
}

void append(struct node** first, int data){

  struct node* last;
  last = (struct node*)malloc(sizeof(struct node));

/*  printf("Enter the data\n");
  scanf("%d",&last->data); */
  last->data = data;

  last->next = NULL;

  struct node* pre = *first;
  if(*first == NULL){
    *first = last;
  }
  while(pre->next!=0)
  {pre = pre->next;}

  last->next = pre->next;
  pre->next = last;
}

void print(struct node* first){

   if(first==NULL){
     printf("There is no linked list to print\n");
   }

   while(first!=NULL){
     printf("%d ",first->data);
     first = first->next;
   }
   printf("\n");
}
int main()
{

   struct node* first=NULL;
   append(&first, 6);
   push(&first, 7);
   push(&first, 1);
   append(&first, 4);
   insert_node(first->next, 8);
   printf("The Linked List is: \n");
   print(first);
   return 0;
}

你在追加函数中得到了你的 segv:

void append(struct node** first, int data){

    struct node* last;
    last = (struct node*)malloc(sizeof(struct node));
    last->data = data;

    last->next = NULL;

    struct node* pre = *first; // <-- pre = NULL
    if(*first == NULL){
        *first = last;
    }

    while(pre->next!=0)
    {pre = pre->next;} //<-- referencing NULL

    last->next = pre->next;
    pre->next = last;
}

解决方法:在if.

里面加一个return
if(*first == NULL){
    *first = last;
    return;
}