0

I am attempting to create my own HashMap to understand how they work. I am using an array of Linked Lists to store the values(strings) in my hashmap.

I am creating the array like this:

Node** list;

Instead of this:

Node* list[nSize];

This is so the array can be any size at runtime. But I think I am getting a memory leak because of how I am doing this. I dont know where the error is but when I run the following simple code the .exe crashes.

Why is my application crashing and how can I fix it?

Note: I am aware that using a vector would be much better than an array but this is just for learning and I want to challenge myself to create the hashmap using a 'Dynamic' Array. PS: is that the correct term(Dynamic Array) for the kind of array I am using?

struct Node
{
  // to implement
};

class HashMap
{
  public:
     HashMap(int dynSize)
     {
        *list = new Node[dynSize];
        size  = dynSize;  

        for (int i=0; i<size; i++)
            list[i] = NULL;

        cout << "END\n";
     }

     ~HashMap()
     {
        for (int i=0; i<size; i++)
           delete list[i];
     }

  private:
     Node** list; // I could use a vector here but I am experimenting with a pointer to an array(pointer), also its more elegant
     int    size;
};

int main()
{
   // When I run this application it crashes. Where is my memory leak?
   HashMap h(5);

   system("PAUSE");
   return 0;
}
sazr
  • 24,984
  • 66
  • 194
  • 362

2 Answers2

1

You need to follow the Rule of Three.

Provide a copy constructor and copy assignment operator which make deep copies of the dynamically allocated member.

Besides,

 Node** list; 
 *list = new Node[dynSize];

Just deferences an uninitialized pointer. *list does not point to anything meaningful since list was never initialized.

Community
  • 1
  • 1
Alok Save
  • 202,538
  • 53
  • 430
  • 533
0

As Alok Save mentioned, you are dereferencing an uninitialized pointer. The key here is that you have a double pointer which requires a two step initialization. First, you must allocate memory to list:

// note that I'm using 'X', simply using 'size' doesn't work for two dimensions
list = new Node*[X];

Now that you have X Node pointers, you need to make each one point to Y nodes.

for (int i = 0; i < X; i++)
    list[i] = new Node[Y];

You would probably want to do some error handling if new isn't able to allocate memory, but this will at least get the Node** built.

To destroy this, just do it in reverse order, but remember to use delete[], since you allocated it with new[].

for (int i=0; i < X; i++)
    delete[] list[i];
delete[] list;
smskelley
  • 161
  • 1
  • 7