可能未初始化的本地指针变量(C ++)

时间:2018-10-29 22:12:49

标签: c++ nodes

在“占位符-> next = NULL;”行上我收到一个潜在的未初始化局部变量的错误。任何建议表示赞赏。

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

2 个答案:

答案 0 :(得分:2)

编译器看不到以下事实

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

由于以前的工作流程,至少运行了一次。

更安全的是始终初始化变量:

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

(即使延迟nullptr是UB,也就是延迟未初始化的指针。)

更好的是减小变量的范围,这可以使初始化更好:

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

答案 1 :(得分:1)

在声明名为占位符的指针时,只需编写

placeholder=nullptr