2012-01-28 48 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; 
}