【问题标题】:Deleting C++ classes (valgrind check)删除 C++ 类(valgrind 检查)
【发布时间】:2013-11-28 14:49:18
【问题描述】:

我有一个 HashMap 类,一切似乎都运行良好,但是我遇到了内存泄漏问题。

下面是我的 HashMap 类私有成员变量/函数

   struct Node
    {
        std::string key;
        std::string value;
        Node* next;
    };

    HashFunction hashfunction;
    Node** bucketList;
    int* numberOfPairs; 
    int logins;
    int lengthOfMap;

这是我的默认构造函数:

 HashMap::HashMap()
    :hashfunction(hash), bucketList(bucketList = new Node*[INITIAL_BUCKET_COUNT]), numberOfPairs(numberOfPairs = new int[INITIAL_BUCKET_COUNT]),
    logins(0),lengthOfMap(INITIAL_BUCKET_COUNT)
{
    for(int i = 0; i < INITIAL_BUCKET_COUNT; i ++)
    {
        bucketList[i] = nullptr;
    }
    zeroFillArray(numberOfPairs, INITIAL_BUCKET_COUNT);
}

我有bucketList指针,指向一个Node数组,每个Node指向一个链表的开头。

到目前为止,这是我的析构函数:

HashMap::~HashMap() 
{
    delete numberOfPairs;
    delete bucketList;
}

我是在删除列表之前删除列表中的每个节点(我会在早上解决这个问题,但我想问一下),还是我完全遗漏了其他东西?

【问题讨论】:

  • 您为什么不阅读 Valgrind 生成的诊断并自己解决这个问题?
  • 是的,您删除了每个节点。指针永远不会删除自己。

标签: c++ pointers hashmap delete-operator


【解决方案1】:
HashMap::~HashMap() 
{
    for(int i = 0; i < INITIAL_BUCKET_COUNT; i ++)
    {
        Node* node  = bucketList[i];
        while( node != nullptr)
        {
            Node* next = node->next;
            delete node;
            node = next;
        }
    } 
    delete numberOfPairs;
    delete[] bucketList;
}

【讨论】:

  • 这是否会删除每个指向 bucketList[i] 中第一个节点的指针?这似乎只会删除链表而不删除第一个节点指针。
【解决方案2】:

您必须手动从bucketList 中删除每个节点。说手动我的意思是你应该扔掉每个节点并删除它。 像这样:

HashMap::~HashMap() 
{
    for(int i = 0; i < INITIAL_BUCKET_COUNT; ++i)
    {
        if( bucketList[i] )
        {
            Node* first = bucketList[i];
            while( first )
            {
                Node* temp = first->next;
                delete first;
                first = temp;
            }
        }
    }
    delete[] bucketList;
    delete numberOfPairs;
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2016-03-16
    • 2016-08-08
    • 1970-01-01
    • 2012-01-01
    • 2023-03-18
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多