0
votes

I have a hash table of nodes. In my constructor, I initialize every element of the hash table to NULL. My code compiles, but after the executable ends, it has the following error: "Debug Assertion Failed!" Program: /pathname/ File:f:\dd\vctools\crt_bld\self_x86\crt\src\dbgdel.cpp line: 52

Expression: _BLOCK_TYPE_IS_VALID(pHead->nBlockUse)

My Implementation for constructor and destructor:

// 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
1
Some of the pointers you are deleting must not be valid. You could add some cerr trace to document the pointers and operations on them, see what's mismatched, but I suggest you use std::unordered_map<> or std::map<> and std::string - you'll find life much easier. - Tony Delroy
Show more code. What is the type of Hash_Table? In the code there is no new for it. delete[] here also seems unreasonable. - Xiangyan Sun
You need a debugger to locate the problem. - Zhongzhi

1 Answers

0
votes

You should create a proper destructor for song if you haven't already. That is delete temp should call song::~song, which deletes all of the members of song other than song->next.

Your destructor for Hash then becomes:

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

I also removed delete[] Hash_Table, because your constructor doesn't new Hash_Table[]. You only want delete[] for arrays of objects you've called new[] on.

Without seeing your full class definition, though, it's hard to see for sure whether my suggestions are fully correct. As others have suggested, you should consider using map<> or unordered_map<> as opposed to trying to roll your own hash. Unless, of course, this is a homework assignment that requires you to.