Jarrod Cabalzar
Jarrod Cabalzar

Reputation: 408

Segmentation out-of-range fault in destructor

I have a segmentation fault in my destructor but I'm not quite sure why. The code is for a map of key/value pairs which are stored in a Node array and chained to avoid collisions.

template<class V>
map<string, V>::~map()
{
    for(unsigned int i = 0; i < SIZE; i++){
        if(hashArray[i] != NULL){
            Node* tmpNode = hashArray[i];
             Node* currentNode = hashArray[i];
            while(currentNode->next != NULL){
                currentNode = currentNode->next;
                delete tmpNode;
                tmpNode = currentNode;
            }
            delete tmpNode;
        }
    }

    delete [] hashArray;
}

The debugger points to this line but I'm sure I'm not going out of range.

while(currentNode->next != NULL){

Any other code can be provided if need be. thank you in advance for your help. :)

Upvotes: 0

Views: 286

Answers (1)

Open AI - Opting Out
Open AI - Opting Out

Reputation: 24164

I cleaned it up a bit by getting rid of the duplicate hashArray[i]s. Also got rid of the duplicate checks for null:

template<class V>
map<string, V>::~map()
{
    for(unsigned int i = 0; i < SIZE; i++) {
        Node* currentNode = hashArray[i];
        while(currentNode) {
            Node* next = currentNode->next;
            delete currentNode;
            currentNode = next;
        }
    }

    delete [] hashArray;
}

Upvotes: 1

Related Questions