electric fan
electric fan

Reputation: 53

Dereferencing null pointer warning and code run stuck infinitely

So i am trying to solve a problem to reverse a linked list and following is what i came up with.

class Solution
{
public:

   /* void insertList(struct Node* head, int data)
    {
        Node* temp{ head };
        while (temp->next != nullptr)
        {
            temp = temp->next;
        }
        Node* nextNode{ new Node(data) };
        temp->next = nextNode;
    }*/
    void insertPrev(struct Node* revHead, int data)
    {
        Node* temp{ new Node(data) };
        temp->next = revHead;
        revHead = temp;
    }
    //Function to reverse a linked list.
    struct Node* reverseList(struct Node* head)
    {
        if (head == NULL)
            return head;
        Node* revHead{ new Node(head->data) };
        Node* temp{ head->next };
        while (temp != NULL);//this line
        {
            insertPrev(revHead, temp->data);//this line 2
            temp = temp->next;
        }
        return revHead;
    }
};

when i am trying to run this code to reverse a linked list. it gets stuck infinitely on this line which i have commented as this line. Moreover, ide throws warning also that i may be potentially derefercing a null pointer in this line 2. I don't know how is that possible when i just checked above that temp should not be null for the while loop to run. Help please!

Upvotes: -2

Views: 49

Answers (1)

trincot
trincot

Reputation: 351359

You have two issues in your code:

  • while (temp != NULL);//this line represents an infinite loop. The semicolon represents an empty body for this while construct. Remove it.

  • insertPrev modifies a local variable revHead: the caller's variable with the same name will not be modified by it. To fix this, define the parameter as pass-by-reference: void insertPrev(struct Node* &revHead, int data) (add the &).

This will fix the issue.

Other remarks

As this is C++ code:

  • Don't declare variables with struct Node*, but just Node*.
  • Don't use a mix of NULL and nullptr: only use nullptr

Depending on what was asked in the challenge, you could solve this by reversing the linked list in place, without needing to create new nodes.

Upvotes: 1

Related Questions