简体   繁体   中英

equation double pointer to NULL gives segmentation fault in C

#include<stdio.h>
#include<malloc.h>

typedef struct Node {
 int data;
 struct Node * next;
} Node;


void push(Node **headRef, int i){
//why does headRef == NULL in below if condition gives segmentation fault?
  if(*headRef == NULL){
    *headRef = malloc(sizeof(Node));
    Node *head = *headRef;
    head->data = i;
  }
}

int main(int argc, char ** argv){
  Node *head = NULL;
  push(&head, 2);
  printf("%d\n", head->data);
}

This code is of linked list where I try to push some data into the list. My question is in the comment of push function.

是的,segfault稍后会在head->data访问中(如果您使用headRef==NULL

No need for the test. If *headRef happens to be NULL, newnode->next will be set to NULL, otherwise to *headRef.

void push(Node **headRef, int i){
    Node *new;

    new = malloc(sizeof *new);
    /* check for new==NULL omitted */
    new->next = *headRef;
    new->data = i;
    *headRef = new;
 }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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