-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;
}
這是代碼,導致段故障線路? – satheeshwaran
C沒有分段故障的概念。未定義行爲的行爲 - 按定義 - 未定義。我們不是一個調試服務,閱讀[問]。只是:你的功能接口已經壞了。 C嚴格按價值傳遞。 – Olaf
[不要在C中輸入'malloc'的結果](http://stackoverflow.com/q/605845/995714) –