samedi 3 novembre 2018

Memory leak with hash table

So essentially, I have created a hash table within a class and am attempting to implement an addWord function and destructor that prevent memory leaks, however, I keep getting them and have no clue as to why. I have posted the method definitions below. Sorry if the formatting is poor, this is my first post. Thanks.

wordItem * createNode(string word, wordItem* next)
{
    wordItem* nw = new wordItem;
    nw->word = word;
    nw->next = next;
    nw->count = 0; 
    return nw;
}


void HashTable::addWord(string word)
{
    if(!searchTable(word))
    {
        numItems++; 
        int index = getHash(word); 
        wordItem * n = createNode(word, nullptr); 

        if(hashTable[index] == nullptr)
        {
            hashTable[index] = n; 
        }

        else
        {
            n->next = hashTable[index]; 
            hashTable[index] = n; 
            numCollisions++; 
        }

    }

    incrementCount(word); 
}




HashTable::~HashTable() 
{
    wordItem* temp;
    wordItem* next;

    for(int i = 0; i < hashTableSize; i++) 
    { 
        temp = hashTable[i];

        while(NULL != temp) 
        {
            next = temp->next;
            delete temp;
            temp = next;
        } 

        hashTable[i] = NULL;
    } 
} 

Aucun commentaire:

Enregistrer un commentaire