educative.io

Memory leak + improper usage of new

You have a memory leak. Using new is unnecessary because the vector is going to use a copy constructor to move that data into its storage. Using new like this would be fine in C# or Java but not C++.
for (int i = 0; i < keySpace; i++) {
Bucket *bucket = new Bucket;
bucketList.push_back(*bucket);
}

To avoid a memory leak use:
for (int i = 0; i < keySpace; i++) {
bucketList.push_back(Bucket());
}

or clean up your memory
for (int i = 0; i < keySpace; i++) {
Bucket *bucket = new Bucket;
bucketList.push_back(*bucket);
delete bucket;
}


Course: Grokking Coding Interview Patterns in C++ - Learn Interactively
Lesson: Solution: Design HashMap - Grokking Coding Interview Patterns in C++

Hi @Vincent_Liguori,
I appreciate you bringing this to my attention. The codes have been revised and the problem has been resolved.

1 Like