Search code examples
c++pointershashmapdelete-operator

Deleting C++ classes (valgrind check)


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?


Solution

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