Frage

I have a class HashMap, and everything seems to be working fine, however I'm having a problem with memoryleaks.

Below are my HashMap class private member variables/functions

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

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

And here is my default constructor:

 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);
}

I have the bucketList pointer, pointing to an array of Nodes, and each Node points to the beginning of a linked list.

As of now, this is my destructor:

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

Do I delete EACH Node (I'll tackle this in the morning, but I wanted to ask regardless) within the list before I delete the list, or am I missing something else entirely?

War es hilfreich?

Lösung

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;
}

Andere Tipps

You have manualy to delete every node from your bucketList. Saying manualy i mean you should go throw every node and delete it. Like this:

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;
}
Lizenziert unter: CC-BY-SA mit Zuschreibung
Nicht verbunden mit StackOverflow
scroll top