C 如何消除空分段错误?
我正在用C语言创建一个链表程序,我不断地遇到一个分段错误。我已经将问题缩小到了几行代码,我相信这与检查NULL有关。我怎样才能解决这个问题?代码如下:C 如何消除空分段错误?,c,pointers,segmentation-fault,C,Pointers,Segmentation Fault,我正在用C语言创建一个链表程序,我不断地遇到一个分段错误。我已经将问题缩小到了几行代码,我相信这与检查NULL有关。我怎样才能解决这个问题?代码如下: typedef struct node { int contents; struct node *nextNode; } Node; deleteNode(Node *currentNode) { while((currentNode->contents) != NULL) { //.....Do Stuf
typedef struct node
{
int contents;
struct node *nextNode;
} Node;
deleteNode(Node *currentNode)
{
while((currentNode->contents) != NULL)
{
//.....Do Stuff.....
currentNode = currentNode->nextNode;
}
}
谢谢请尝试检查以确保
currentNode
在deleteNode()
的开头处不是NULL
。即
deleteNode(Node *currentNode)
{
if (currentNode == NULL) return;
// ...
// ...
}
尝试检查以确保
deleteNode()
开头的currentNode
不是NULL
。即
deleteNode(Node *currentNode)
{
if (currentNode == NULL) return;
// ...
// ...
}
如果问题如我所怀疑的那样,
currentNode
是一个空指针。只需确保currentNode
在尝试访问它之前不为null
deleteNode(Node* currentNode)
{
while ((currentNode != NULL) && (currentNode->contents != NULL))
{
/* ... */
currentNode = currentNode->nextNode;
}
}
如果问题如我所怀疑的那样,
currentNode
是一个空指针。只需确保currentNode
在尝试访问它之前不为null
deleteNode(Node* currentNode)
{
while ((currentNode != NULL) && (currentNode->contents != NULL))
{
/* ... */
currentNode = currentNode->nextNode;
}
}
我怀疑这句话:
while((currentNode->contents) != NULL)
正在比较节点
结构的内容
字段,该结构是int
,与NULL
。。。我猜这应该是检查currentNode->nextNode
因此,很可能:您的
内容都不为零,因此此测试对列表中的每个项目都是正确的。然后最后一个项目有一个空的currentNode->nextNode
,它被分配给currentNode
,并且它在下一次循环中取消对它的引用。好吧,我怀疑这一行:
while((currentNode->contents) != NULL)
正在比较节点
结构的内容
字段,该结构是int
,与NULL
。。。我猜这应该是检查currentNode->nextNode
因此,很可能:您的内容都不为零,因此此测试对列表中的每个项目都是正确的。然后最后一个项目有一个NULLcurrentNode->nextNode
,它被分配给currentNode
,并且它在下一次循环中取消对它的引用。当currentNode为NULL时会发生什么?。它在while条件下解除对空内存的引用 当currentNode为NULL时会发生什么?。它在while条件下解除对空内存的引用 顺便说一句。。。如果这个deleteNode函数应该从链表中删除一个节点,它就不能。如果侧注上只有指向要删除的节点的指针(除非根节点可以全局访问,或者当然可以访问),则无法从单独相似的列表中删除节点。。。如果这个deleteNode函数应该从链表中删除一个节点,它就不能。您不能仅使用指向要删除的节点的指针从单独喜欢的列表中删除节点(除非您的根节点是全局可访问的,或者当然是全局可访问的)