Search code examples
c++nodes

Potentially uninitialized local pointer variable (C++)


On the line "placeholder->next = NULL;" I get an error of a potential uninitialized local variable. Any advice is appreciated.

Node * ptr;
Node * placeholder;
if (head == NULL)
{
    cout << "Please add something to the list before deleting." << endl;
    return menu();
}
else
{
    if (head->next == NULL)
    {
        ptr = head;
        head = NULL;
        free(ptr);
    }
    else
    {
        ptr = head;
        while (ptr->next != NULL)
        {
            placeholder = ptr;
            ptr = ptr->next;
        }

        placeholder->next = NULL;
        free(ptr);
    }
}

Solution

  • Compiler fail to see the fact that

    while (ptr->next != nullptr)
    {
        placeholder = ptr;
        ptr = ptr->next;
    }
    

    runs at least once due to previous workflow.

    Safer is to always initialize variable:

    Node* ptr = nullptr;
    Node* placeholder = nullptr;
    

    (even if deferencing nullptr is UB, as deferencing uninitalized pointer.)

    Even better is to reduce scope of the variable, which allow to give better initalization:

    if (head == nullptr)
    {
        std::cout << "Please add something to the list before deleting." << std::endl;
        return menu();
    }
    if (head->next == nullptr)
    {
        Node* ptr = head;
        head = nullptr;
        free(ptr);
    }
    else
    {
        Node* placeholder = head;
        Node* ptr = head->next;
    
        while (ptr->next != nullptr)
        {
            placeholder = ptr;
            ptr = ptr->next;
        }
    
        placeholder->next = nullptr;
        free(ptr);
    }