2016-02-29 107 views
-1

試圖研究鏈表,並在終端和Xcode的gcc 4.1.2上試用我的程序。代碼= 1) 終端錯誤;分割錯誤鏈接列表程序錯誤?在C

我不知道xcode錯誤是什麼。出於某種原因,它給了我一些在其他gcc上工作的程序的相同錯誤?

代碼:

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

typedef struct node *link; 
struct node {int item; link next;}; 

int main(int argc, const char * argv[]) { 

    int i; 
    link t = malloc(sizeof *t); 
    while (t != NULL) 
    { 
     for (i = 0; i < 10;i++) 
     { 
      t->item = i; 
      t = t->next; 
     } 
    } 
    int count = 0; 
    while (t != NULL) 
    { 
     for (i = 0; i < 10; i++) 
     { 
      if (count == 3) 
      { 
       printf("%d\n", t->item); 
       continue; 
      } 
      t = t->next; 
      count++; 
     } 
    } 
} 
+3

'malloc'給你一個未初始化的內存塊。 't = t-> next'很可能會產生一個非法的指針。您還爲一個節點分配內存,然後嘗試從中創建十個節點的鏈接列表。創建時,您必須爲每個節點分配內存。另外,如果在打印第三個節點時繼續循環,則永遠不會增加節點數量或增加計數。你的意思是'破壞'?最後,什麼是'malloc'ed必須是'free'd。 –

回答

1

您解除引用t->next,這是通過malloc()分配和未分配一定的價值,並調用未定義的行爲。您必須爲第二個節點和稍後分配緩衝區。

另外,在處理清單之前,您應該拿回指針t

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

typedef struct node *link; 
struct node {int item; link next;}; 

int main(int argc, const char * argv[]) { 

    int i; 
    link t = malloc(sizeof *t); 
    link head = t; /* add this line to get the pointer back */ 
    while (t != NULL) 
    { 
     for (i = 0; i < 10;i++) 
     { 
      t->item = i; 
      t->next = malloc(sizeof *t); /* add this line */ 
      t = t->next; 
     } 
    } 
    int count = 0; 
    t = head; /* add this line to get the pointer back */ 
    while (t != NULL) /* convinated with inner loop, this will lead to infinite loop */ 
    { 
     for (i = 0; i < 10; i++) /* you may want to check if t != NULL here for safety */ 
     { 
      /* not invalid but odd program that print the 4th element again and again */ 
      if (count == 3) 
      { 
       printf("%d\n", t->item); 
       continue; 
      } 
      t = t->next; 
      count++; 
     } 
    } 
}