0

我有一个类 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 指针,指向一个节点数组,每个节点都指向一个链表的开头。

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

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

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

4

2 回答 2

3
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;
}
于 2013-11-15T09:11:34.660 回答
0

您必须手动从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;
}
于 2013-11-15T09:16:50.040 回答