2016-02-29 181 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++; 
     } 
    } 
}