I wrote this hash map (this was a part of telephonic interview exercise), where I do a new Node(key, value) when I put an element. I want to make sure I’m cleaning up when the hashmap itself goes out of scope.
Did I miss anything in here ? Is there any way I can check if there is a memory leak ?
class HashMap {
private:
list<Node*> data[SIZE];
public:
~HashMap();
Node* get(int key);
void put(int key, int value);
int hashFn(int val){ return val % 13; }
};
HashMap::~HashMap(){
for(int i = 0; i < SIZE; ++i){
list<Node*>& val = data[i];
for(list<Node*>::iterator it = val.begin(); it != val.end(); it++){
Node* n = *it;
delete n;
}
}
}
For the curios: complete code is here: http://rextester.com/EHPCYW12862
EDIT:
Also, do I really need to call list.clear() in the end (since I’ve already deallocated all the nodes in a list) ?
It seems
putis constructing aNodeto put into your hash table, associating thekeyandvalue. There was no need to use alist<Node *>, it would have been cleaner to uselist<Node>instead.Then, you could have avoided implementing a destructor.
Your
getfunction can still return a pointer.If you leave the implementation with
list<Node *>, then you should also implement a copy constructor and an assignment operator (the rule of three).