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?
}
The code as written now only has one serious flaw; you delete the list chained to
head, but never set head toNULL. 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
headshould beNULLafter this is done anyway, forego usingcurrentNodeat all. Simply useheaditself 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 yourfree_memory()function, as it should be.