如何解决seg故障?

时间:2016-10-20 04:41:20

标签: c

当主要功能在其他.c文件中时,此代码在我的Mac上有段错误。当main函数和这个函数在同一个文件中时,它运行良好。

List *search( int k )   
{       
List *current = head->next;

   while (current != NULL && current->data != k)
      current = current->next;

   if (current != NULL && current->data == k)
   {
      printf("data is found!%d\n", current->data);
      return current;
   } 

   return NULL;  
}

1 个答案:

答案 0 :(得分:0)

在删除功能中,如果列表变空,则必须更新tail

int removeFirst()
{
   List *nodeToRemove;
   int dataToRemove;

   if (head->next == NULL)
   {
      prtError("Empty list!");
      return -1;
   }
   else
   {
      nodeToRemove = head->next;
      dataToRemove = nodeToRemove->data;
      head->next = nodeToRemove->next;
      free(nodeToRemove);

      // Update tail if list is empty
      if (head->next == NULL)
      {
          tail = head;
      }

      return dataToRemove;
   }
}