Hayden Gfeller
Hayden Gfeller

Reputation: 19

Link list error, c++

In my user made link list which I'm using to hold an inventory for the text based rpg I am making, I am encounter an error with my delete function, within my link list. I was wondering if someone could point out to me why I am getting this error.

void InventoryList::deleteNode(int num)
{
    ListNode *previousNode; //To point to the previous node
    ListNode *nodePtr; //to traverse the list

    int number = 1;

    //if the head is empty do nothing
    if (!head)
    {
        return;
    }
    //Determine if the first node is the value
    if (1 == num)
    {

        nodePtr = head->next;
        delete head;
        head = nodePtr;
    }
    else
    {
        //intialize the node as head.
        nodePtr = head;


        //Skip nodes whose value is not equal to num.
        while (nodePtr != nullptr && number != num)
        {
            previousNode = nodePtr;
            nodePtr = nodePtr->next;

            number++;
        }
        if (nodePtr)
        {
        previousNode->next = nodePtr->next;
        delete nodePtr;
        }
    }
}

I am encountering this error with the final if statement of the code, and the error is:

error C4703: potentially uninitialized local pointer variable 'previousNode' used

Upvotes: 0

Views: 109

Answers (1)

C-Kennelly
C-Kennelly

Reputation: 68

R Nar's comment has it right. The while loop where you initialize PreviousNode isn't guaranteed to run, so the pointer is potentially uninitialized - thus, your error message.

To fix it, you need to initialize PreviousNode in a block that is guaranteed to run - no if/while/etc.

This could go anywhere, but I'd recommend setting it to NULL when you declare it, and check to ensure it's not null when you use it. Always a good habit to initialize when you declare and check your pointers.

Upvotes: 1

Related Questions