如何摆脱NULL分段错误?

时间:2011-09-18 05:36:06

标签: c pointers segmentation-fault

我正在用C创建链接列表程序,并且我继续遇到分段错误。我已经将问题缩小到几行代码,我相信它与检查NULL有关。我怎样才能解决这个问题?这是代码:

typedef struct node
{
  int contents;
  struct node *nextNode;
}  Node;



deleteNode(Node *currentNode)
{

  while((currentNode->contents) != NULL)
  {
    //.....Do Stuff.....
    currentNode = currentNode->nextNode;
  }
}

由于

4 个答案:

答案 0 :(得分:7)

尝试检查以确保在currentNode开头时NULL不是deleteNode()。即。

deleteNode(Node *currentNode)
{
    if (currentNode == NULL) return;
    // ...
    // ...
}

答案 1 :(得分:4)

如果问题是我怀疑的那样,currentNode是一个空指针。在尝试访问它之前,请确保currentNode不为空。

deleteNode(Node* currentNode)
{
    while ((currentNode != NULL) && (currentNode->contents != NULL))
    {
        /* ... */
        currentNode = currentNode->nextNode;
    }
}

答案 2 :(得分:0)

好吧,我怀疑这一行:

while((currentNode->contents) != NULL)

contents结构的Node字段(int}与NULL进行比较...我猜这应该是在检查{ {1}},而不是!

因此,可能:您的currentNode->nextNode都不为零,因此对于列表中的每个项目,此测试均为真。然后最后一个项目有一个NULL contents,它被分配给currentNode->nextNode,并且它会在下一次循环时将其解除引用。

答案 3 :(得分:0)

当currentNode为NULL时会发生什么?它在while条件下取消引用NULL内存。

相关问题