Linked List destructor without head? - c++

I'm stuck on a linked list destructor for my class. This is what I have here:
LinkedList::~LinkedList()
{
LinkedList *forward = nullptr;
LinkedList *current = this;
//iterate through list, deleting each element as we go
while (current != nullptr)
{
//set next pointer to current's next
forward = current->next;
delete current; //delete the current memory
current = forward; //reset current to next's pointer
}
}
When I run it, I get a seg fault. I only want to delete just one node from my linked list. Is that possible? Also, I wasn't given a "head" pointer as I was used to from other lists, so I used "this" instead, does that work?
Aka - the .cpp is finding the spot in the linked list to delete, reorganizing the next pointers around it, and then deleting the node (which calls this destructor)
(when I run my program with an empty destructor, it prints out fine, but of course there are memory leaks)
Any help is appreciated!

by definition delete calls LinkedList::~LinkedList, so you have several (in fact infinite) calls to it because of the loop calling delete, so you access to already deleted element with an undefined behavior
just do
LinkedList::~LinkedList()
{
if (next != nullptr)
delete next;
}
or just
LinkedList::~LinkedList()
{
delete next; // delete on nullptr does nothing
}
even personally I prefer to compare to nullptr first

I argee with bruno.
Besides, when you want to delete a node and you don't have the pointer to head, you need a double-linked list.
The double-linked list has two pointers to its prev and next node.
when you need to delete a node, like this:
ListNode* p;
if(p->pre)
p->pre->nxt = p->nxt;
if(p->nxt)
p->nxt->pre = p->pre;
p->nxt = p->pre = NULL;
delete p;

Related

why cannot "delete at head" work correctly when implementing link-list?

I implement the following code to delete element at Head. When program runes to "delete p", it will impact the previous Head and Head gets to NULL. What happened?
Node<T>* p;
p = Head;
Head = Head->next;
delete p;
This function will delete the 1st node (node
pointed to by head). It returns true if the node was deleted else false if the list is empty.
Using double pointers for the input parameter (head) here because head will
have to be updated and this value should reflect
outside this function.
bool deleteHeadElement(Node** head)
{
if (*head == nullptr)
{
// List is empty, nothing to delete
return false;
}
// Store the node that has to be deleted
Node* nodeToDelete = *head;
// Update the head to point to next nodeToDelete
*head = nodeToDelete->next;
delete nodeToDelete;
// 1st element of node has been deleted.
return true;
}
After the call to this function, you may subsequently call it and it will take care of the scenario in which the list becomes empty after the previous calls.
NOTE:
Regarding the value 0xfeeefeee, it seems you are trying to somehow freeing already freed memory. Perhaps you should check if your head is properly getting updated.
Also, make sure that you are freeing memory of the node by using delete only if it was allocated using new. delete takes care if the memory to pointed is NULL.
If you had allocated memory to the node using malloc(), you should be deallocating using free().

Is this a effective way to delete entire linked list?

In function given below, I simply delete the head-pointer of the list and set head pointer to nullptr (im setting it nullptr because in my print function,I check for nullptr for head node, and ask user to create list first if head-node is nullptr).
void del_list(stud* &orig_head)
{
cout << "Deleting entire list..." << endl;
delete orig_head;
orig_head = nullptr;
}
I have a question regarding the way I choose to delete the list, since im not clearing each node of list, im simply clear the head pointer, what will happen to all the other nodes? Will this approach create a memory leak ?
Edit:
Im not using OOP to implement linked list,im implementing linked list using struct and couple of functions.
I like to handle this problem recursively:
void deleteNode(Node * head)
{
if(head->pNext != NULL)
{
deleteNode(head->pNext)
}
delete head;
}
If we have a list of 5 items:
head->pNext->pNext->pNext->pNext->NULL;
Then, the function will first get called for head, then for each pNext until the last one. When we reach the last one, it will skip deleting the next one (since it's null) and just delete the last pNext. Then return and delete the list from back to front.
This is assuming that each node's pNext is initialized to NULL. Otherwise, you'll never know when you've reached the end of the linked list.
Your code will cause memory leak. To delete it correctly, traverse the list and while traversing delete each node separately. And finally make head pointer to point to NULL value. You can have a look at the following code.
void deleteList(struct Node** head_ref)
{
struct Node* current = *head_ref;
struct Node* next;
while (current != NULL)
{
next = current->next;
free(current);
current = next;
}
//Now make head_ref point to null
*head_ref = NULL;
}

Deleting a node from the start of a linked list

I am implementing a stack using a singly linked list where the Head is at the top of the stack and the Tail is at the bottom of the stack.
I am implementing a pop operation. In order to do this, I must make the head equal to the second node in the linked list. But before I do this, I need to delete the first node in the linked list first. I can do this using delete head->next;.
My question is, if I delete that first node, can I still use it to move on to the next node? Or is it bad practice to use a reference of a node that has had delete called on it. Here is the code I want to use to implement pop.
delete head->next;
head->next = head->next->next;
If you do:
delete head->next;
Then head->next is invalid. If you try to dereference it in the next line (remember the right hand side will be evaluated before the assignment), your program will crash.
head->next = head->next->!next; // dereference of the bad pointer happens where I put the !, and you crash there.
If you want to delete the object at head->next you will need to save it off first.
p = head->next;
head->next = head->next->next;
delete p;
First, once something is deleted, it is gone. Don't access deleted memory.
Second, why are you saying head->next = head->next->next? Shouldn't head = head->next be good enough for pop? In a empty list, head would be nullptr, wouldn't it?
Third, why are you not using std::list?
Last, order of operation is sometimes important, especially when the linked list might be shared by multiple threads. This is how I'd implement pop (and optionally make it multithread safe):
void list::pop() {
// optionally, acquire mutex
node* to_be_deleted = head;
head = head->next;
if (head == nullptr) tail = nullptr;
// release optional mutex here
delete to_be_deleted;
}

Using the destructor to free linked objects

I have a class called "node". I link a bunch of node objects together to form a linked list. When the "node" destructor is called, it only deletes the first node. How do I iterate through the entire linked list of nodes and delete each node object?
Here is the class definition:
class Node
{
private:
double coeff;
int exponent;
Node *next;
public:
Node(double c, int e, Node *nodeobjectPtr)
{
coeff = c;
exponent = e;
next = nodeobjectPtr;
}
~Node()
{
printf("Node Destroyed");
}
The destructor is called by invoking delete on the pointer to the first node of the linked node list.
Since you don't know how many nodes there are in a list, if you do not have firm bounds on that it's not a good idea to invoke destructors recursively, because each call uses some stack space, and when available stack space is exhausted you get Undefined Behavior, like a crash.
So if you absolutely want to do deallocate following nodes in a node's destructor, then it has to first unlink each node before destroying it.
It can go like this:
Node* unlink( Node*& p )
{
Node* result = p;
p = p->next;
result->next = nullptr;
return result;
}
Node::~Node()
{
while( next != nullptr )
{
delete unlink( next );
}
}
But better, make a List object that has ownership of the nodes in a linked list.
Of course, unless this is for learning purposes or there is a really good reason to roll your own linked list, just use a std::vector (and yes I mean that, not std::list).
How do I iterate through the entire linked list of nodes and delete each node object?
It would be cleaner if you had a separate class to manage the entire list, so that nodes can be simple data structures. Then you just need a simple loop in the list's destructor:
while (head) {
Node * victim = head;
head = victim->next; // Careful: read this before deleting
delete victim;
}
If you really want to delegate list management to the nodes themselves, you'll need to be a bit more careful:
while (next) {
Node * victim = next;
next = victim->next;
victim->next = nullptr; // Careful: avoid recursion
delete victim;
}
Under this scheme, you'll also need to be careful when deleting a node after removing it from the list - again, make sure you reset its pointer so it doesn't delete the rest of the list. That's another reason to favour a separate "list" class.

C++ delete not working?

I am having a problem with delete and destructor (I am sure I am making a stupid mistake here, but haven't been able to figure it out as of yet).
When I step through into the destructor, and attempt to call delete on a pointer, the message shows up "Cannot access memory at address some address."
The relevant code is:
/*
* Removes the front item of the linked list and returns the value stored
* in that node.
*
* TODO - Throws an exception if the list is empty
*/
std::string LinkedList::RemoveFront()
{
LinkedListNode *n = pHead->GetNext(); // the node we are removing
std::string rtnData = n->GetData(); // the data to return
// un-hook the node from the linked list
pHead->SetNext(n->GetNext());
n->GetNext()->SetPrev(pHead);
// delete the node
delete n;
n=0;
size--;
return rtnData;
}
and
/*
* Destructor for a linked node.
*
* Deletes all the dynamically allocated memory, and sets those pointers to 0.
*/
LinkedListNode::~LinkedListNode()
{
delete pNext; // This is where the error pops up
delete pPrev;
pNext=0;
pPrev=0;
}
It seems that you are deleting the next and previous nodes of the list from the destructor. Which, if pNext and pPrev are LinkedListNode*, means that you are recursively deleting the whole list :-(
Try this:
std::string LinkedList::RemoveFront()
{
LinkedListNode *n = pHead->GetNext(); // the node we are removing
std::string rtnData = n->GetData(); // the data to return
// un-hook the node from the linked list
pHead->SetNext(n->GetNext());
n->GetNext()->SetPrev(pHead);
n->SetNext(0);
n->SetPrev(0);
// delete the node
delete n;
n=0;
size--;
return rtnData;
}
LinkedListNode::~LinkedListNode()
{
}
(Actually you don't even need to reset the prev and next pointers to 0 since you are going to delete the node anyway. I left those statements in because they at least put the node into a consistent state, which is a good idea in general. It may make a difference if you later e.g. change your memory management strategy and decide to store unused nodes for later reuse.)
It seems that your LinkedListNode is deleting its neighbours, so when you delete one node it then proceeds to destroy the entire list - note you don't set pNext and pPrev to NULL when you remove your node.
Also your LinkedListNode destructor is problematic even in the case when you want the whole list to be destroyed: having both delete pNext and delete pPrev will lead to multiple calls of the same destructor (and I think eventually a stack overflow).
Actually you shouldn't be messing with neighbours in a node. That's for list class to do - connect them properly. In the destructor you can set them to null, but unless you have allocated dynamically something else - you don't have to call delete