Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

I don't understand what I'm doing wrong with my de-allocation of memory

So I have a linked list getting created correctly, linked properly but when I try to de-allocate memory I can't seem to delete any node, the list still exists. Code for my list deconstructor:

void LL_User::free_memory() {
    // TODO
    LL_User_Node *currentNode;
    currentNode = head;
    while(currentNode) {
        LL_User_Node *temp = currentNode;
        currentNode = currentNode->next;
        delete temp;
    }
    //cout << "LL_User::free_memory() is not implemented yet.\n";
}

LL_User::~LL_User() {
    if(head == NULL) {
        return;
    }
    free_memory();
}

And my user class has this for the vars and deconstructor:

User::User() {
    username = "";
    password = "";
    first_name = "";
    last_name = "";
    profile_pic_filename = "";
    birth_year = 0;
    birth_month = 0;
    birth_day = 0;
}

User::~User() {
    //Nothing placed in body because strings and ints are dealt with by OS?
}
like image 301
gndimitro Avatar asked Dec 11 '25 07:12

gndimitro


1 Answers

The code as written now only has one serious flaw; you delete the list chained to head, but never set head to NULL. Anyone touching it from this point on is hitting undefined behavior through a garbage pointer.

Set head to NULL if you're wiping the list like this. Alternatively, since you know head should be NULL after this is done anyway, forego using currentNode at all. Simply use head itself as the pointer that is walking the list. Think about that for awhile and it will come to you.

Also, as-written the check for (head == NULL) is not needed in your destructor. It is already checked in your free_memory() function, as it should be.

like image 175
WhozCraig Avatar answered Dec 13 '25 00:12

WhozCraig



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!