Philip Wald
Philip Wald

Reputation: 43

Destructor always hitting Null

I´m currently playing around with linked lists today. I got everything to work just fine though I always seem to run into the same Problem,the destructor no matter what, it seems to always run into a NULL object when accessing the destructor in any form, throwing an "access rights violation Error"

"this->next" was "0xDDDDDDDD".

struct Liste {
Liste *next;
int content;
Liste() {
    content = 0;
    next = nullptr;
};
~Liste() {
    if (next == nullptr) {
        return;
    }else if (next->next == nullptr){
        delete next;
        return;
    }else {
        next->~Liste();
    }
};
};

I´m quite unsure and curious about what could be the source for this Error. It always occurs no matter the way i try to use delete on it. The solutions i found so far were: -simply call delete on the first element and it calls the destructor of the others -try to check if next in line IS Null but it doesn´t seem to filter it out at all -try to go through it iteratively but that too did run into ground zero -try to implement it in a class which did work just as fine as this did, up to the point i had to implement a deletion which ran into the exact same Error

Id be happy to receive some tips on how to fix/avoid this since not deleting it at all cant be a good idea, and i'm not sure at all what exactly went wrong in the code.

Upvotes: 1

Views: 130

Answers (2)

Matthias
Matthias

Reputation: 4677

Without a stack overflow compared to the previous answer:

~Liste() {
     Liste* temp = nullptr;
     while (next) {
         temp       = next->next;
         next->next = nullptr;
         delete next;
         next       = temp;
     }
 }

With regard to the given code:

~Liste() {
    if (next == nullptr) {
        return;
    } else if (next->next == nullptr){
        delete next;
        return;
    } else {
        next->~Liste(); // *next is destructed, but next is not deallocated!
    }
};

Though, the given code (including the destructor) is probably not the reason for the bad memory access as already mentioned by Slava.

Upvotes: 1

javidcf
javidcf

Reputation: 59711

Your destructor just needs to do:

~Liste() {
    delete next;
}

If next is not null, then delete next; will call the destructor of the next element, which in turn will call the destructor of the next element, and so on. If next is null then delete next; will not do anything, which is fine.

Upvotes: 1

Related Questions