So, I created my own constructors for structs that used pointers thinking I'd do a great memory management, when actually I'm not. When I used the version 1 of hashF, I got the double free error. When I used the version 2, I didn't. Could you please explain to me why? I'm still learning to manage the memory properly.
struct Vect {
int* arr;
int sz=0;
Vect(int n = 5){
this->sz = n;
arr = new T[n];
}
~Vect()
{
delete[] arr;
}
};
struct Node
{
bool empty = true;
uint32_t ckey;
Vect<int> positions;
Node(uint32_t key = 0)
{
if(key != 0){
empty = false;
ckey = key;
}
}
};
struct HT
{
Node* arr;
int capacity;
int numele=0;
float ocupation=0;
HT(int n)
{
arr = new Node[n];
capacity = n;
}
~HT()
{
delete[] arr;
arr = nullptr;
}
};
version 1:
int hashF(uint32_t ckey, Node* &nodearr, int mode=0)
{
uint p0 = ckey % capacity;
for(int i=0; i<capacity; i++)
{
int pos = (p0 + i) % capacity;
Node N = nodearr[pos];
bool a = N.empty;
if(mode == 0)
{
if(N.empty == true)
return pos;
}else
{
if(!((!N.empty) && (N.ckey != ckey)))
return pos;
}
}
return -1;
}
version 2:
int hashF(uint32_t ckey, Node* &nodearr, int mode=0)
{
uint p0 = ckey % capacity;
for(int i=0; i<capacity; i++)
{
int pos = (p0 + i) % capacity;
Node *N = &nodearr[pos];
bool a = N->empty;
if(mode == 0)
{
if(N->empty == true)
return pos;
}else
{
if(!((!N->empty) && (N->ckey != ckey)))
return pos;
}
}
return -1;
}