【问题标题】:c++ Deleting multiple head/tail of linked list stored in vectorc ++删除存储在向量中的链表的多个头/尾
【发布时间】:2020-05-14 03:45:12
【问题描述】:

我一直在尝试将链表的头部和尾部存储到向量中并将其用作容器。 所以向量将有 { head_1stLL, tail_1stLL, head_2ndLL, tail_2ndLL ...}

问题是当我试图清理这个向量中的链表时。我找不到删除链表的方法。 调用 CleanVector 后,我使用 target.clear()。 向量似乎是空的,但我仍然将内存分配给以前的链接列表并且能够访问所有内容。

为了简单起见,在我大修我的代码以使用 2D 矢量之前,我很想知道出了什么问题。

struct node
{
    Document doc;
    node* next;
    node* prev;
    char LBnType; //Leg type and base definition
}
void cleanVector(std::vector <node*> &target)
{
    node* temp;
    if(target.size()%2 ==0 )
    {
        while(!target.empty())
        {

            node* head = target.front();
            temp = head;

            target.erase(target.begin());
            node* tail = target.front();
            target.erase(target.begin());
            deepCleanLL(head, tail);



            if(temp != NULL) // here it says not deleted
            {
                cout << "FAILED TO DELETE" << endl;
                printList(temp); //this was to test if I can still access LL
            }

        }


    }
    else
        cout << "ERROR: nodeDeepCleanVector. Target size not even" << endl; 
}

void deepCleanLL(node* &begin, node* &end)
{

    node* current = end;
    node* temp = begin;
    while(current == NULL)
    {
        node* currentLag = current;
        current = current->prev;
        current->next = NULL; 
        current->prev = NULL;
        delete currentLag;
        currentLag = current;
    }
        if(temp != NULL)
        {//temp here says LL is cleaered
            cout<< "delete failed" << endl;
            printList(temp);
        }


}

【问题讨论】:

    标签: c++ vector linked-list


    【解决方案1】:

    C++ 中没有规定不能访问已删除的内存。

    如果你尝试访问已删除的内存,那么你的程序有undefined behaviour (UB),而不是 C++ 所说的。这意味着您的程序可以做任何事情,并且任何事情都包括能够访问已删除的内存,就像它没有被删除一样。

    初学者常常认为,当他们的代码出现错误时,就意味着他们的程序必须崩溃或者必须产生错误的结果,或者必须产生错误信息。但这不是真的,所有这些事情可能都会发生,但也可能是程序似乎可以工作。所有这些事情都可能发生,因为它们都被未定义的行为所覆盖。

    这意味着要区分正确的程序和不正确的程序要困难得多,因为有时错误的程序会按预期工作。

    除了在删除后尝试打印列表之外,您的代码在我看来是正确的。

    【讨论】:

    • 感谢您的快速回复。你介意再帮我一个问题吗?当我运行程序时,每次我删除充满链表的向量并给它新的链表时,我都会偶然发现内存总是翻倍。我正在使用 mingw 开发这个程序,并且由于 64 位环境而无法使用 valgrind 并且 drmemory 崩溃。所以我没有可靠的工具来查看正在发生的事情。在我看来,如果内存被释放,我希望看到 ram 内存(显示在任务管理器中)保持不变或至少不会翻倍(非常一致)。你觉得我应该担心这个吗?
    • 当它的内存被删除时,它被释放以供回程序而不是回系统。所以删除的内存不会在任务管理器中显示为减少的内存使用。通常,只有在程序退出时才会将内存释放回系统。
    • 非常感谢。这一直困扰着我一段时间
    【解决方案2】:

    找到另一个真正有效的答案。 有严重的编码问题。答案可以在下面的链接中找到。 Deleting a pointer in C++

    问题是我在释放内存之前将指针分配为 NULL,从而留下悬空指针。

    我希望这可以帮助某人。

    【讨论】:

      猜你喜欢
      • 2016-07-06
      • 1970-01-01
      • 1970-01-01
      • 2015-10-14
      • 2020-05-12
      • 2020-05-31
      • 1970-01-01
      • 2021-11-25
      • 1970-01-01
      相关资源
      最近更新 更多