简体   繁体   中英

deleting a hash table in C++

I am building a hash table using arrays and buckets that are represented by linked lists in C++. I am running into something very weird when I try to clear the hash table and I would appreciate it if someone can explain why this is happening.

This code works fine:

for(int i = 0; i < bins; i++)
{
    while(map[i]->next != nullptr)
    {
        LN* toDelete = map[i];
        map[i] = map[i]->next;
        delete toDelete;
    }
}

However for some reason if I do this, it doesn't delete anything anymore:

for(int i = 0; i < bins; i++)
{
    LN* node = map[i]
    while(node->next != nullptr)
    {
        LN* toDelete = node;
        node = node->next;
        delete toDelete;
    }
}

Each bucker is represented by a trailer linked list that's why I'm checking node->next not node. From my okay understanding of pointers, node should refer to the same thing as map[i] so when I call delete on node it should delete the object that both map[i] and node refer to.

Thank you in advance

Your code does delete everything. What it doesn't do is changing map[i] pointer to point to an empty list element (with next set to nullptr ) at the end, so it ends up pointing to a deleted object.

This means that map[i] is dangling . Dereferencing it is undefined behavior. This can be fixed by assigning map[i] the value of node after the loop:

LN* node = map[i];
while(node->next != nullptr)
{
    LN* toDelete = node;
    node = node->next;
    delete toDelete;
}
map[i] = node;

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