1

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 it 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

1
  • On a side note ... if this deleteNode function is supposed to delete a node from a linked list, it can't. You can't delete a node from a singly liked list with only a pointer to the node you want to delete (unless your root node is accessible globally, or course) Commented Sep 18, 2011 at 5:51

4 Answers 4

7

Try checking to make sure that currentNode isn't NULL at the start of deleteNode(). I.e.

deleteNode(Node *currentNode)
{
    if (currentNode == NULL) return;
    // ...
    // ...
}
Sign up to request clarification or add additional context in comments.

Comments

4

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;
    }
}

Comments

0

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.

Comments

0

what happens when currentNode is NULL?. It is dereferencing a NULL memory in the while condition.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.