2012-01-28 53 views
2
#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); 
} 

此代码是链接列表,我尝试将某些数据推送到列表中。 我的问题是在推送功能的评论。等式双指针为NULL给出了C中的分段错误

+0

我没有看到该行的任何错误。 – NPE 2012-01-28 12:34:10

+0

在标准C中,'malloc'生活在''中,而不是''。我无法重现错误。 – 2012-01-28 12:36:42

+1

除此之外,您的代码运行良好。你的问题必须在其他地方。 – 2012-01-28 12:37:37

回答

0

是,段错误是后来在head->data访问(如果您使用headRef==NULL

+0

代码更改* headRef == NULL,headRef == NULL,则会出现段错误 – Govind 2012-02-07 00:23:53

0

无需进行测试。如果* headRef恰好为NULL,则newnode-> next将设置为NULL,否则设置为* 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; 
}