【问题标题】:Destructor for hash table using chaining使用链接的哈希表的析构函数
【发布时间】:2013-11-19 06:47:34
【问题描述】:

我有一个节点哈希表。在我的构造函数中,我将哈希表的每个元素都初始化为 NULL。我的代码可以编译,但可执行文件结束后,出现以下错误: “调试断言失败!” 程序:/路径名/ 文件:f:\dd\vctools\crt_bld\self_x86\crt\src\dbgdel.cpp 行:52

表达式:_BLOCK_TYPE_IS_VALID(pHead->nBlockUse)

我的构造函数和析构函数的实现:

// Constructor
Hash::Hash() {
    for(int i = 0; i < tableSize; i++) {
        Hash_Table[i] = NULL; // Will be used to indicate an empty bucket
     } 
}
//
//
// Destructor
Hash::~Hash() {
    song* temp;
    song* temp_next;
    for(int i = 0; i < tableSize; i++) { // For every bucket
        if(NULL != Hash_Table[i]) { // If the bucket is not already empty
            temp = Hash_Table[i];
            while(NULL != temp) {
                delete[] temp->artist;
                delete[] temp->title;
                delete[] temp->playlists;
                delete[] temp->album;
                temp_next = temp->next;
                delete temp;
                temp = temp_next;
            } // end while loop
            Hash_Table[i] = NULL;
        } // end if
    } // end for loop
    delete[] Hash_Table;
} // end destructor

【问题讨论】:

  • 您要删除的某些指针一定是无效的。您可以添加一些 cerr 跟踪来记录指针和对它们的操作,看看有什么不匹配的,但我建议您使用 std::unordered_map&lt;&gt;std::map&lt;&gt;std::string - 你会发现生活更轻松。
  • 显示更多代码。 Hash_Table 的类型是什么?在代码中没有newdelete[]这里也显得不合理。
  • 你需要一个调试器来定位问题。

标签: c++ hash hashtable


【解决方案1】:

如果您还没有为song 创建适当的析构函数,则应该这样做。那就是delete temp应该调用song::~song,这样就删除了song除了song-&gt;next之外的所有成员。

Hash 的析构函数会变成:

Hash::~Hash() {
    song* temp;
    song* temp_next;
    for(int i = 0; i < tableSize; i++) { // For every bucket
        temp = Hash_Table[i];
        while(NULL != temp) {
            temp_next = temp->next;
            delete temp;
            temp = temp_next;
        } // end while loop
        Hash_Table[i] = NULL;
    } // end for loop
} // end destructor

我还删除了delete[] Hash_Table,因为您的构造函数没有new Hash_Table[]。您只需要 delete[] 用于您已调用 new[] 的对象数组。

但是,如果没有看到您的完整类定义,很难确定我的建议是否完全正确。正如其他人建议的那样,您应该考虑使用map&lt;&gt;unordered_map&lt;&gt;,而不是尝试滚动自己的哈希。当然,除非这是一项需要你做的家庭作业。

【讨论】:

    猜你喜欢
    • 2013-12-23
    • 2011-02-27
    • 1970-01-01
    • 1970-01-01
    • 2012-05-06
    • 2021-06-25
    • 2012-10-27
    • 1970-01-01
    • 2017-05-17
    相关资源
    最近更新 更多