Reputation: 111
Everytime the code tries to insert the values from the old array into the new array in the grow function, I get an error "Error reading characters of string". I am trying to grow the array when it reaches a certain load factor. I have tried to figure out what the problem is but I don't know what it is. I have provide code for the grow, insert, and choosePrime function. The main problem is in the grow function, but I don't know if one of these other functions is affecting it.Any help is appreciated!
void grow() {
int newCapacity = choosePrime();
Slot **tmp = table;
table = new Slot*[newCapacity];
for (int i = 0; i < capacity; i++) {
table[i] = NULL;
}
for (int i = 0; i < capacity; i++) {
if (tmp[i] != NULL) {
Insert(tmp[i]->key, tmp[i]->value);
delete tmp[i];
}
}
capacity = newCapacity;
delete[] tmp;
}
/* Chooses Prime Number */
int choosePrime() {
int n = capacity * 2;
bool foundMultiple = false;
do {
n++;
for (int i = 1; i < n; i++) {
if (n % i == 0) {
foundMultiple = true;
}
}
} while(foundMultiple == false);
return n;
}
bool Insert(string key, int value)
{
if (float(size) / float(capacity) >= 0.5) {
grow();
}
int h = hash(key);
if (table[h] == NULL)
{
size++;
table[h] = new Slot;
table[h]->key = key;
table[h]->value = value;
table[h]->nextSlot = nullptr;
return true;
}
else if (table[h]->key == key)
{
return false;
}
else
{
int p = probe(key, 1);
for (int i = 1; h != p; p = probe(key, ++i))
{
if (table[p] == NULL)
{
size++;
table[p] = new Slot;
table[p]->key = key;
table[p]->value = value;
return true;
}
else if (table[p]->key == key)
{
return false;
}
}
return false;
}
}
Upvotes: 0
Views: 32
Reputation: 32727
In grow
, after allocating memory for a new table, you only set the original capacity
elements to NULL
. The "new" elements, from capacity
to newCapacity
are uninitialized.
Change your initialization loop to
for (int i = 0; i < newCapacity; i++)
Upvotes: 2