【发布时间】:2013-11-17 04:21:18
【问题描述】:
我创建了一个哈希表类,并以这种方式编写了它的析构函数
HashMap::~HashMap()
{
for (int i=0; i<cap; i++)
{
Node* ptr = Hashtable[i];
while (ptr)
{
Node* delptr;
delptr=ptr;
ptr=ptr->next;
delete delptr;
}
}
delete [] Hashtable;
}
既然有析构函数,为什么还要一直泄漏内存?
这是我如何实现构造函数
HashMap::HashMap()
{
Hashtable= new Node* [INITIAL_BUCKET_COUNT];
sz=0;
cap=INITIAL_BUCKET_COUNT;
hashfunction=defaulthashfunction;
}
additem函数是:
void HashMap::add(const std::string& key, const std::string& value)
{
int index = hashfunction(key)%cap;;
Node* ptr=Hashtable[index];
Node* newnode=new Node;
if (contains(key)==false)
{
if (ptr == nullptr)
{
newnode->key=key;
newnode->value=value;
newnode->next=NULL;
Hashtable[index]=newnode;
}
else
{
newnode->key=key;
newnode->value=value;
newnode->next=NULL;
while(ptr->next != NULL)
{
ptr = ptr->next;
}
ptr->next=newnode;
}}
if (loadFactor() > 0.8)
{
int newcap = cap*2+1;
Node** newhash = new Node* [newcap];
rehash(newhash, Hashtable, cap, newcap);
for (int i=0; i <cap; i++)
{
Node* ptr=Hashtable[i];
while (ptr)
{
Node* delptr;
delptr=ptr;
ptr=ptr->next;
delete delptr;
}
}
delete [] Hashtable;
Hashtable=newhash;
}
}
这是我的 rehash 函数,唯一的错误总是这一行: Node* nnode = new Node; 如果我将此代码放在循环之外,则错误变为 20,这表明问题出在我的析构函数中。但在调整我的哈希表大小之前,它没有错误,我测试了几次。为什么rehash函数会一直泄漏内存?
void HashMap::rehash(Node** newhash, Node** oldhash, int oldcap, int newcap)
{
for (int x=0; x<newcap; x++)
{
newhash[x]=NULL;
}
//Node* nnode = new Node;
for (int i = 0; i<oldcap; i++)
{
Node* ptr=oldhash[i];
while (ptr!=NULL)
{
int index = hashfunction(ptr->key)%newcap;
Node* nptr=newhash[index];
Node* nnode = new Node;
if (nptr==NULL)
{
nnode->key=ptr->key;
nnode->value=ptr->value;
nnode->next=NULL;
newhash[index]=nnode;
}
else
{
while (nptr->next != NULL)
{
nptr=nptr->next;
}
nnode->key=ptr->key;
nnode->value=ptr->value;
nnode->next=NULL;
nptr->next=nnode;
}
ptr=ptr->next;
}
}
}
-- 插入--
【问题讨论】:
-
你确定
HashMap::~HashMap()真的被调用了吗?在相关的不,停止使用未初始化的数据评估。如果您不知道这些是什么,int a; if (a < 10)...就是一个例子。另一个:int *p; if (p != nullptr)...这样做会调用未定义的行为。 -
如果无法看到您的声明,就无法判断您是否进行了适当的清理。
-
如何初始化数据?我需要调用~HashMap()吗???否则,为什么不被调用。
标签: c++ memory-leaks hashmap hashtable