How do I get rid of a NULL segmentation fault?
I am creating a linked list program in C and I keep on getting a segmentation fault. I've narrowed the problem down to a few lines of code and I believe i开发者_如何学Pythont has to do with checking for NULL. How can I fix this? Here's the code:
typedef struct node
{
  int contents;
  struct node *nextNode;
}  Node;
deleteNode(Node *currentNode)
{
  while((currentNode->contents) != NULL)
  {
    //.....Do Stuff.....
    currentNode = currentNode->nextNode;
  }
}
Thanks
Try checking to make sure that currentNode isn't NULL at the start of deleteNode(). I.e.
deleteNode(Node *currentNode)
{
    if (currentNode == NULL) return;
    // ...
    // ...
}
If the problem is as I suspect, currentNode is a null pointer. Just ensure that currentNode is not null before you attempt to access it.
deleteNode(Node* currentNode)
{
    while ((currentNode != NULL) && (currentNode->contents != NULL))
    {
        /* ... */
        currentNode = currentNode->nextNode;
    }
}
Well, I'm suspicious that this line:
while((currentNode->contents) != NULL)
is comparing the contents field of your Node structure, which is an int, with NULL...  I would guess that this was supposed to be checking currentNode->nextNodeinstead!
So, probably: none of your contents are zero, so this test is true for every item in the list.  Then the last item has a NULL currentNode->nextNode, which is assigned to currentNode, and it blows up dereferencing it the next time round the loop.
what happens when currentNode is NULL?. It is dereferencing a NULL memory in the while condition.
 
         加载中,请稍侯......
 加载中,请稍侯......
      
精彩评论