【问题标题】:weird container memory leak奇怪的容器内存泄漏
【发布时间】:2014-06-24 13:27:50
【问题描述】:

我正在尝试使用链表方法构建我自己版本的 std 容器之一。每次获得新数据时,我都会创建一个新节点并将其放入容器中。 D'tor 会在容器销毁时销毁所有节点。

奇怪的是,在进行泄漏检查(使用 valgrind)之后,每次插入第一个数据时它都会说我有泄漏。这是插入代码:

template<typename A, typename T>
typename container<A, T>::Iterator Queue<A, T>::insert(
        const A& priority, const T& object) {
    Iterator head = this->begin();
    Iterator tail = this->begin();
    this->findElementPlace(priority, head, tail);
    Node<A, T> *newNode = new Node<A, T>(priority, object);
    head.node->next = newNode;
    newNode->next = (tail.node);
    ++head;
    (this->Psize)++;
    return head;
}

它一直将我引向这一行:

Node<A, T> *newNode = new Node<A, T>(priority, object);

Node 类非常基础:

template<typename A, typename T>

class Node {

public:
    Element<A, T> element;
    Node* next;
    Node() :
                element(), next(NULL) {
        }
        Node(const A priority, const T data) :
                element(priority, data), next(NULL) {
        }
        ~Node() {
        }
    };

第一个数据存储在哪里并不重要,它总是说特定数据不会被删除,尽管 D'tor 会处理它。它使用擦除功能从第一个到最后一个擦除所有元素。这是主循环:

while ((from < to) && (from < this->end())) {
    it.node->next = from.node->next;
    Iterator temp = from;
    ++from;
    delete temp.node;
    (this->Psize)--;
}

它删除迭代器“from”到迭代器“to”之间的所有节点,包括“from”,不包括“to”

有谁知道如何解决这个问题?

【问题讨论】:

  • 任何你不使用某种形式的引用计数智能指针的原因,例如std::shared_ptr?
  • 你的迭代器是什么样的?

标签: c++ memory-leaks new-operator


【解决方案1】:

我发现了问题。 迭代器包含一个索引参数,operatorend()”都被重新计算,但迭代器“from”和“to”不再相关,因为它们的索引不再相关。 我对其索引添加了更新,以便这次容器中的所有元素都将被释放。 新的擦除循环是:

while ((from < to) && (from < this->end())) {
    it.node->next = from.node->next;
    Iterator temp = from;
    from.index--;
    ++from;
    delete temp.node;
    (this->Psize)--;
    to.index--;
}

【讨论】:

    猜你喜欢
    • 2012-07-06
    • 1970-01-01
    • 2015-05-09
    • 2021-03-28
    • 2020-12-19
    • 2011-04-01
    • 2012-03-07
    • 2018-06-28
    相关资源
    最近更新 更多