简体   繁体   中英

Clearing a hash table in C++

I have create a clear () function, which when is called, clears the entire Hash Table and resets the size to 0. The function is causing memory leaks in my program but I do not see a possible leak.. Here is my clear() function:

void HashMap::clear()
{

unsigned int capacity = HashMap::bucketCount();

for (unsigned int i = 0; i < capacity; i++)
{
    Node* temp;
    Node* StoreThenDel = new Node;

    if (HashTable[i] != nullptr)
    {
        temp = HashTable[i];
        HashTable[i] = nullptr;

        while(temp->next != nullptr)
        {
            StoreThenDel = temp;

            if(StoreThenDel->next != nullptr)
                  temp = StoreThenDel->next;

            delete StoreThenDel;
        }

     }

}

  sz=0; // reset size
}

You do a StoreThenDel = new Node . This allocates memory for a Node on the heap. Afterwards you do a StoreThenDel = temp , losing the information about where you allocated memory for the Node on the heap.

Node* StoreThenDel = new Node;

This new is a leak and is unnecessary.

while(temp->next != nullptr)

This loop condition stops too soon. It should run until temp != nullptr . As is it leaks the last entry in each list.

  if(StoreThenDel->next != nullptr)
       temp = StoreThenDel->next;

That assignment of temp should not be conditional.

Your while loop and temp variables are just very confusing, try to simplify the code to something like the below and you will find that the simpler code has fewer problems.

for (unsigned int i = 0; i < capacity; ++i)
{
    while (HashTable[i] != nullptr)
    {
         Node* temp = HashTable[i];
         HashTable[i] = temp->next;
         delete temp;
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM