我正在写一个 C++ 哈希表
这是我的析构函数:
HashMap::~HashMap()
{
for (int i=0; i<cap; i++)
{
Node* ptr = Hashtable[i];
while (ptr!=NULL)
{
Node* delptr;
delptr=ptr;
ptr=ptr->next;
delete delptr;
}
}
delete [] Hashtable;
}
我的添加功能:
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;
}}}
但我不断收到内存泄漏错误
==13676==
==13676== HEAP SUMMARY:
==13676== in use at exit: 12 bytes in 1 blocks
==13676== total heap usage: 42 allocs, 41 frees, 669 bytes allocated
==13676==
==13676== 12 bytes in 1 blocks are definitely lost in loss record 1 of 1
==13676== at 0x402BE94: operator new(unsigned int) (in /usr/lib/valgrind/vgpreload_memcheck-x86-linux.so)
==13676== by 0x804BF8D: HashMap::add(std::string const&, std::string const&) (HashMap.cpp:112)
==13676== by 0x804AFD2: main (main.cpp:18)
==13676==
==13676== LEAK SUMMARY:
==13676== definitely lost: 12 bytes in 1 blocks
==13676== indirectly lost: 0 bytes in 0 blocks
==13676== possibly lost: 0 bytes in 0 blocks
==13676== still reachable: 0 bytes in 0 blocks
==13676== suppressed: 0 bytes in 0 blocks
==13676==
==13676== For counts of detected and suppressed errors, rerun with: -v
==13676== ERROR SUMMARY: 1 errors from 1 contexts (suppressed: 0 from 0)
其指示的行是 Node* newnode=new Node;因为我这里使用了“new”,所以这个newnode需要被释放,但析构函数只释放Hashtable中的内容。如果我不使用“newnode”,则会出现空指针访问错误,因为nullptr无法访问Node(Node是一个有键和值的结构体),我只能让指针指向“newnode”。然而,添加额外的“删除新节点”会让我收到 20 多个错误。我真的需要你的帮助!
如果我这样写,我仍然会收到错误
if (contains(key)==false)
{
if (ptr == nullptr)
{
Node* newnode=new Node;
newnode->key=key;
newnode->value=value;
newnode->next=NULL;
Hashtable[index]=newnode;
}
else
{
Node* newnode=new Node;
newnode->key=key;
newnode->value=value;
newnode->next=NULL;
while(ptr->next != NULL)
{
ptr = ptr->next;
}
ptr->next=newnode;
}}