【问题标题】:How do I get rid of a NULL segmentation fault?如何摆脱 NULL 分段错误?
【发布时间】:2011-09-18 05:36:05
【问题描述】:

我正在用 C 语言创建一个链表程序,但我不断遇到分段错误。我已将问题缩小到几行代码,我相信它与检查 NULL 有关。我怎样才能解决这个问题?代码如下:

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



deleteNode(Node *currentNode)
{

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

谢谢

【问题讨论】:

  • 附带说明......如果这个deleteNode函数应该从链表中删除一个节点,它不能。您不能仅使用指向要删除的节点的指针从单个喜欢的列表中删除节点(除非您的根节点可以全局访问,或者当然)

标签: c pointers segmentation-fault


【解决方案1】:

尝试检查以确保currentNode 不是NULLdeleteNode() 的开头。即

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

【讨论】:

    【解决方案2】:

    如果问题如我所料,currentNode 是一个空指针。在尝试访问之前确保currentNode 不为空。

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

    【讨论】:

      【解决方案3】:

      好吧,我怀疑这条线:

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

      正在比较您的Node 结构的contents 字段,这是一个int,与NULL... 我猜这应该是检查currentNode->nextNode

      所以,很可能:您的contents 都不是零,所以这个测试对于列表中的每个项目都是正确的。然后最后一项有一个NULL currentNode->nextNode,它被分配给currentNode,它在下一次循环中取消引用它。

      【讨论】:

        【解决方案4】:

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

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 2021-06-30
          • 2021-09-28
          • 2019-06-07
          • 1970-01-01
          • 2017-04-04
          • 2011-08-07
          • 1970-01-01
          相关资源
          最近更新 更多