如何在 C++ 中编写正确的哈希表析构函数

2023-12-01

我正在写一个 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;
     }}

这条线

Node* newnode=new Node; 

创建一个本地 newnode 指针,该指针在 add 函数退出后将超出范围。这将泄漏 new 分配的内存。

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

如何在 C++ 中编写正确的哈希表析构函数 的相关文章

随机推荐