链接列表程序错误?在C.

时间:2016-02-29 08:14:14

标签: c linked-list

尝试研究链表并在终端和Xcode上的gcc 4.1.2上尝试我的程序。

xcode错误:线程1:Exe_BAD_ACCESS(代码= 1) 终端错误;分段错误

我不知道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++;
        }
    }
}

1 个答案:

答案 0 :(得分: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++;
        }
    }
}