2017-07-25 198 views
-2

分段故障發生的原因有哪些? 在下面的代碼中,我試圖創建一個簡單的方法來使用鏈接列表。 基本上在我的程序中,您只需使用linkedList結構類型創建一個列表。 但是,程序中有一行會導致分段錯誤。爲什麼會發生? 任何幫助將不勝感激。謝謝:)爲什麼會出現分段錯誤?

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

struct node{ 
    int num; 
    struct node *next; 
}; 
//Make the struct 

typedef struct { 
    struct node * first; 
    struct node * current; 
}linkedList; 

void addNode(linkedList list, int a); 
void addFirstNode(linkedList list, int b); 
//Function prototypes 

int main() { 

    linkedList list; 
    addFirstNode(list, 1); 
    addNode(list, 2); 
    addNode(list, 3); 
    addNode(list, 4); 
    addNode(list, 5); 
    addNode(list, 6); 
    addNode(list, 7); 
} 

void addFirstNode(linkedList list, int input) { 

    list.first = (struct node *)malloc(sizeof(struct node)); //Make first node 
    list.first -> num = input;         //Fill first node 
    list.current = list.first;          
} 
void addNode(linkedList list, int input) { 

    struct node * newNode = (struct node *)malloc(sizeof(struct node)); 
    newNode -> num = input;      
    list.current -> next = newNode; //Segmentation fault! (core dumped) 
    list.current = newNode; 
} 
+1

這是代碼,導致段故障線路? – satheeshwaran

+1

C沒有分段故障的概念。未定義行爲的行爲 - 按定義 - 未定義。我們不是一個調試服務,閱讀[問]。只是:你的功能接口已經壞了。 C嚴格按價值傳遞。 – Olaf

+0

[不要在C中輸入'malloc'的結果](http://stackoverflow.com/q/605845/995714) –

回答

0

正如在評論中指出,有許多東西在你的代碼來糾正:

  • 你需要按引用傳遞函數的參數(C按值傳遞的元素) 。
  • 你需要初始化你的鏈表,否則你會試圖解引用NULL指針。

下面的代碼的正確版本:

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

struct node{ 
    int num; 
    struct node *next; 
}; 
//Make the struct 

typedef struct { 
    struct node * first; 
    struct node * current; 
}linkedList; 

void addNode(linkedList* list, int a); 
void addFirstNode(linkedList* list, int b); 
//Function prototypes 

int main() { 

    linkedList *list = (struct node *)malloc(sizeof(struct node));; 
    addFirstNode(list, 1); 
    addNode(list, 2); 
    addNode(list, 3); 
    addNode(list, 4); 
    addNode(list, 5); 
    addNode(list, 6); 
    addNode(list, 7); 
} 

void addFirstNode(linkedList* list, int input) { 

    list->first = (struct node *)malloc(sizeof(struct node)); //Make first node 
    list->first->num = input;         //Fill first node 
    list->current = list->first; 
} 
void addNode(linkedList *list, int input) { 

    struct node * newNode = (struct node *)malloc(sizeof(struct node)); 
    newNode->num = input; 
    list->current->next = newNode; //Segmentation fault! (core dumped) 
    list->current = newNode; 
}