删除(ptr-> next)和删除q(q = ptr-> next)之间的区别是什么?

时间:2018-03-24 11:31:10

标签: c++ memory-leaks

代码是针对linkList的,我想释放已删除节点的内存,但是一种方法会导致内存泄漏。两种方式有什么区别?

bool LinkList::deleteElement(int i, EleMentType &e) {
    int j = 0;
    List Ptr = linkList;
    while (Ptr->Next && j < i - 1) {
        Ptr = Ptr->Next;
        j++;
    }

    if (!Ptr->Next || j > i - 1) {
        std::cout << "Failed to delete an element\n";
        return false;
    }

    // Memory Leak
    // Ptr->Next = Ptr->Next->Next;
    // e = Ptr->Next->Data;
    // delete Ptr->Next;

    /* without Memory Leak */
    List q = Ptr->Next;
    Ptr->Next = q->Next;
    e = q->Data;
    delete q;

    return true;
}

1 个答案:

答案 0 :(得分:1)

区别在于您没有删除相同的节点:

Ptr->Next = Ptr->Next->Next;  // modifies Ptr->Next, original value is lost
e = Ptr->Next->Data;          // Ptr->Next may be null, causing undefined behavior
delete Ptr->Next;             // deleting a node that is still pointed to by the list, potential future undefined behavior.

请注意,隐藏在typedef后面的指针被认为是错误的样式。

另请注意,您无法使用此函数删除第一个节点(偏移0),尽管编写直接为此目的修改linkList的代码会很容易。