How to write a correct Hash Table destructor in c++

穿精又带淫゛_ 提交于 2019-12-01 09:30:46

This line

Node* newnode=new Node; 

creates a local newnode pointer which will go out of scope after the add function exits. This will leak memory allocated by new.

The problem is that you are doing this:

Node* newnode=new Node;
if (contains(key)==false)
    // ... store it
/*
else
    leak it
*/

What you need to do is do the conditional BEFORE the new.

if(contains(key) == true) {
     // use the existing entry.
     ...
     return;
}
else {
    Node* newnode=new Node;
    // ... rest of your code for inserting a new entry here.
}

---- Edit ----

What ValGrind is telling you is that your code allocated a pointer at HashMap.cpp line 112, but it never stored the address -- this is what happens in your code when someone calls the add function with a key for which "contains(key)" does not return false. You don't store the pointer, and so the Node you allocated is left allocated but your code is not tracking it -> it's a leak.

Simply declare the newnode and then after the if statement allocate the new Node. The way your code is right now the newnode can be allocated , the if statement goes wrong and the newnode stays in memory never used.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!