-3
我一直試圖在C中實現一個LinkedList
以實際實現我在C中學到的理論。我一直得到一個Segmentation fault: 11.
任何有關如何解決這個問題的幫助將不勝感激。這裏是我的代碼:Segmentation Fault 11,C
#include <stdio.h>
#include <stdlib.h>
struct Element {
int value;
struct Element *nextElement;
};
struct LinkedList {
struct Element *firstElement;
};
void add(struct LinkedList *list, int value) {
if(list->firstElement == NULL) {
struct Element *newElement;
newElement = malloc(sizeof(struct Element));
newElement->value = value;
list->firstElement = newElement;
} else {
struct Element *lastElement;
lastElement = list->firstElement;
while(lastElement->nextElement != NULL) {
lastElement = lastElement->nextElement;
}
struct Element *newElement;
newElement = malloc(sizeof(struct Element));
newElement->value = value;
lastElement->nextElement = newElement;
}
}
void showAllElements(struct LinkedList *list) {
struct Element *lastElement = list->firstElement;
while(lastElement != NULL) {
printf("%d\n", lastElement->value);
lastElement = lastElement->nextElement;
}
}
int main()
{
struct LinkedList list;
add(&list, 5);
add(&list, 10);
add(&list, 15);
showAllElements(&list);
return 0;
}
先用gdb檢查一下。 –
@SouravGhosh你能告訴我gdb是什麼嗎? –
您使用'malloc'分配的每個內存都應該使用'free'釋放。所以你需要自己管理記憶,那就是做記錄並確保沒有記憶泄漏。請參閱:https://en.wikipedia.org/wiki/C_dynamic_memory_allocation#Common_errors –