2016-03-08 80 views
0

我想在C中實現一個鏈表。我相信我正在創建並插入元素,但每次嘗試循環時都會出現分段錯誤。這裏是我的鏈表代碼:穿越鏈表時的分段錯誤

struct node { 
char **data; 
struct node *next; 
}; 

兩個全局變量來存儲指針頭和尾:

struct node *head; 
struct node *tail; 

代碼中插入一個元素:

void insert(char **args) 
{ 
    struct node* pointer = (struct node*)malloc(sizeof(struct node)); 
    pointer -> data = args; 
    pointer -> next = NULL; 
    if(head == NULL) { 
      head = pointer; 
      tail = pointer; 
    } 
    else { 
      tail -> next = pointer; 
      tail = pointer; 
    } 
} 

然後我試着通過列表並打印數據內容(這成功地打印列表中的元素,但是隨後出現分段錯誤):

int print_list(char **args) 
{ 
    struct node *curPointer = head; 
    if(curPointer == NULL) { 
      printf("%s", "List is empty\n"); 
    } 
    else { 
      printf("%s", "List: "); 
      do { 
        int i; 
        while(curPointer->data[i] != NULL) { 
          printf("%s", tail->data[i]); 
          i++; 
        } 
        printf("%s", "\n"); 
        curPointer = curPointer->next; 
      }while(curPointer->next != NULL); 
    } 
    return 1; 
} 

我的程序中依賴循環遍歷列表的其他函數有類似的分段錯誤問題。使用沒有初始化

+0

注意:他們說[你不應該在C]中輸入'malloc()'的結果(http://stackoverflow.com/questions/605845/do-i-cast-the-result-of -malloc)。 – MikeCAT

+1

建議您使用調試器來幫助您找到問題。 – kaylum

+0

警告:在函數'insert()'中不使用參數'char ** data' – MikeCAT

回答

2
  • 的具有自動存儲持續時間局部變量i的值,因此它會調用未定義的行爲。通過更換int i;int i = 0;
  • 初始化icurPointercurPointer = curPointer->next;變得NULL,解引用curPointer在條件curPointer->next != NULL有很大的機會會導致段故障。
    嘗試使用curPointer != NULL而不是curPointer->next != NULL作爲條件。
+0

感謝您的幫助! –