How to delete an object ( node ) which is in use - c++

I have the following code that inserts item to a double-linked list using iterator. This is how we are asked to do it. The code works, but the problem is that I have absolute memory leak of 24 bytes.
NodeIterator<T> insert(NodeIterator<T> & itrPassed, const T datapassed)
{
Node<T> * newNode = new Node<T>(datapassed);
Node<T>* previousOfCurrent = itrPassed.getCurrent()->previous;
previousOfCurrent-> next = newNode;
newNode -> previous = previousOfCurrent;
newNode -> next = itrPassed.getCurrent();
itrPassed.setCurrent(newNode);
return itrPassed;
}
I know that the problem is caused by this line Node<T> * newNode = new Node<T>(datapassed);. I can't delete the newNode object as I am returning an iterator pointing to it and it is used in my linked list.
How to solve this problem ?

One problem I see is that you are not updating the previous of the current node. The previous of the current node still points to the old node. As a consequence, if you are iterating over the nodes using previous, you are going to skip over the newly created node.
The other problem I see is that you are accessing previousOfCurrent without checking whether it is a valid pointer.
Not sure whether fixing them will fix your memory leak problem.
NodeIterator<T> insert(NodeIterator<T> & itrPassed, const T datapassed)
{
Node<T> * newNode = new Node<T>(datapassed);
Node<T>* previousOfCurrent = itrPassed.getCurrent()->previous;
// Prevent accessing a nullptr
if ( previousOfCurrent != nullptr )
{
previousOfCurrent-> next = newNode;
newNode -> previous = previousOfCurrent;
}
newNode -> next = itrPassed.getCurrent();
// Add this
itrPassed.getCurrent()->previous = newNode;
itrPassed.setCurrent(newNode);
return itrPassed;
}

Related

how can I reverse my Linked list . I wrote following code but this is giving only first node's data as output

Node *reverse(Node *head)
{
Node *answer = NULL, *p = head, *address = NULL;
while (p != NULL)
{
address = p;
address->next = answer;
answer = address;
p = p->next;
}
return answer;
}
In order to reverse a singly linked list, you need to keep one node in memory to be able to relink backwards.
It could look like this:
Node* reverse(Node* head) {
if(head) { // must have at least one node
Node* curr = head->next; // head + 1
head->next = nullptr; // this will be the new last node
Node* next; // for saving next while relinking
while(curr) { // while curr != nullptr
next = curr->next; // save the next pointer
curr->next = head; // relink backwards
head = curr; // move head forward
curr = next; // move curr forward
}
// head now points at the new start of the list automatically
}
return head;
}
Demo
I wrote following code but this is giving only first node's data as output
Because, in reverse() function, you are breaking the link of first node from rest of the list and returning it.
Look at this part of code:
address = p;
address->next = answer;
answer = address;
p = p->next;
In first iteration of while loop this is what happening:
Pointer address will point to head of list (as p is initialised with head) and, in the next statement, you are doing address->next = answer (note that answer is initialised with NULL). So, address->next is assigned NULL. Both, pointer p and pointer address are still pointing same node. After this, you are doing p = p->next, this will assign NULL to p because p->next is NULL. As, p is NULL, the while loop condition results in false and loop exits and function end up returning the first node.
You should assign p to its next before assigning answer to address->next, like this:
while (p != NULL)
{
address = p;
p = p->next; // moved up
address->next = answer;
answer = address;
}
Suggestion:
In C++, you should use nullptr instead of NULL.
Reversing a linked list, in essence, is pretty much flipping the arrows:
Original: A->B->C->D->null
Intermediate: null<-A<-B<-C<-D
Reversed: D->C->B->A->null
void reverseList(void)
{
Node *prev = nullptr;
Node *curr = head;
while (curr)
{
Node *nxt = curr->next;
curr->next = prev;
prev = curr;
curr = nxt;
}
head = prev;
}
The crux of the solution will be to use the previous and current node strategy to loop through the list. On lines two and line 3, I set the prev to null and curr to the head respectively. Next, I set the while loop, which will run until curr is equal to null or has reached the end of the list. In the 3rd and 4th lines of the body of the while loop, I set prev to curr and curr to nxt to help me move through the list and keep the traversal going while keeping track of the previous and current nodes.
I am storing the next of the current node in a temporary node nxt since it gets modified later.
Now, curr->next = prev is the statement that does some work. Flipping of the arrows takes place through this statement. Instead of pointing to the next node, we point the next of the current node to the previous node.
Now, we need to take care of the head node only. On the last line, head=prev, prev is the last node in the list. We set the head equal to that prev node in the list, which completes our code to reverse a list.
Suppose you have any trouble visualizing the algorithm. In that case, you even have the privilege to print the data stored in the current and previous nodes after each line in the while loop for a better understanding.
Hope this helps getting the gist of how we reverse a linked list.

Exception Handled this was Nullptr?

I've been working on this assignment, and been running into this bug I haven't been able to fix for hours. It's saying unhandled exception thrown, read access violation. I heard you're not suppose to deference nullptrs, however I don't believe that's what I'm doing.
void Linkedlist::insertnode(string key, string value) {
Node* newNode; //This points to the following node
Node* cursor; //This will traverse through list
newNode = new Node; //create a new node
newNode->data = new HashEntry(key, value); //Initialize the data
newNode->next = nullptr; //Leave the pointer for the node following after empty at inception;
if (!head) {
head = newNode; //if head is empty, this will make the first user input the head
return;
}
else {
cursor = head;
while (cursor->next)
;
//We'll traverse list to add newNode to tail
cursor->next = newNode; //for now the order doesn't matter since they're strings so we add new cluster to tail
}
}
"read access violation" is most likely an uninitialized variable. It happens when you try to access data from memory outside your program memory. This is a protection mechanism of your system to prevent you from overwriting data you shouldn't.
Therefore I'd recommend checking your definition of the class HashEntry as well as the definition of the Pointer head which isn't in your posted code.
What also came in my view is your infinite loop while (cursor->next);
I get what you're trying to do - iterate over the elements until you're at the end of the list. But you have to use an iterator:
Node* iterator = cursor;
while (iterator)
{
iterator = iterator->next;
}

What faulty logic is causing this push_back(...) function of my linked list to fail?

For some reason
template <typename T> void SinglyLinkedList<T>::push_back ( T v )
{
node * newNode = new node;
newNode->val = v;
newNode->next = NULL;
if (_root != NULL)
{
node * thisNode = _root;
while (thisNode->next != NULL) thisNode = thisNode->next;
thisNode->next = newNode;
}
else
{
_root = newNode;
}
}
has incorrect logic and I need some help figuring out what it is. When I tested
int myArray [] = { 1, 69, -23942, 69, 56, 67 };
SinglyLinkedList<int> myList(myArray, sizeof(myArray)/sizeof(int));
myList.push_back(33);
myList.print();
it printed
1->69->-23942->69->56->33->33->33->33->33-> ...
until the program crashed.
I'll explain my logic so that you can pinpoint where I'm wrong:
node * newNode = new node;
newNode->val = v;
newNode->next = NULL;
creates a new node object on the heap and initializes its value to v and its pointer to the next node as NULL. This is the node that will be added on to the end of the list. The end of the list will either be
(1) a final element whose next is NULL
or
(2) non-existent, meaning there are no elements, hence no final element
For micro-optimability, because I expect case (1) to occur more often I put it inside the if clause that is to follow and put case (2) inside the else clause.
Case (2) occurs if and only if the _root node is NULL, meaning the list is empty, and the handling of it is simply to make that _root be newNode:
else
{
_root = newNode;
}
Case (1) requires finding the final node and setting its next to newNode, which should be accomplished very simply with the 3 lines
node * thisNode = _root;
while (thisNode->next != NULL) thisNode = thisNode->next;
thisNode->next = newNode;
What is the flaw in that logic?
The error is in your constructor. This line:
delete lastNode;
is deleting memory that your are still using (the node that lastnode points to has just been put in your list).
Remove that line.
Edit: further explanation. Once the memory that lastnode points to is freed, the runtime can then use that memory again for another call to new. In your your case you have probably ended up with newNode and thisNode pointing to the same location, causing the node to point to itself.
when you delete last node, the node which its next is null deleted and the previous one next pointer is not null so when you parse the linked list you directed to unknown memory places!!!

Inserting at the tail of a doubly linked list

I'm working with linked lists for my first time and have to create a function that can insert a node at the end of a doubly linked list. So far I have
void LinkedList::insertAtTail(const value_type& entry) {
Node *newNode = new Node(entry, NULL, tail);
tail->next = newNode;
tail = newNode;
++node_count;
}
The Node class accepts a value to be stored, a value for the next pointer to point to, and a value for the previous pointer in that order. Whenever I try to insert a node here, I get an error saying there was an unhandled exception and there was an access violation in writing to location 0x00000008.
I'm not entirely sure what's going wrong here but I assume it has something to do with dereferencing a null pointer based on the error message. I would really appreciate some help with solving this problem.
EDIT:
I should have clarified early, tail is a pointer that points to the last node in the list. Tail->next accesses the next variable of that last node which, before the function runs, points to NULL but after it executes should point to the new node created.
Where does tail point to initially? If it's NULL then you'll dereference a null pointer when trying to insert the first element.
Does it help if you test tail before dereferencing it?
void LinkedList::insertAtTail(const value_type& entry) {
Node *newNode = new Node(entry, NULL, tail);
if (tail)
tail->next = newNode;
tail = newNode;
++node_count;
}
If tail is null and offsetof(Node, next) is 8 that would explain the access violation, because tail->next would be at the address 0x00000000 + 8 which is 0x00000008, so assigning to tail->next would try to write to memory at that address, which is exactly the error you're seeing.
Assuming your LinkedList has both a head AND tail, maybe try:
void LinkedList::insertAtTail(const value_type& entry)
{
Node *newNode = new Node(entry, NULL, tail);
if (tail)
tail->next = newNode;
tail = newNode;
if (!head)
head = newNode;
++node_count;
}
Just a shot in the dark
It's difficult to tell what's causing the error without knowing the state of the list before the insertion operation (which is actually append rather than insert, by the way).
There's a good chance you're not handling the initial case of appending to an empty list. The basic algorithm is (an empty list is indicated by a NULL head pointer, everything else is indeterminate):
def append (entry):
# Common stuff no matter the current list state.
node = new Node()
node->payload = entry
node->next = NULL
# Make first entry in empty list.
if head = NULL:
node->prev = NULL
head = node
tail = node
return
# Otherwise, we are appending to existing list.
next->prev = tail
tail->next = node
tail = node

What is the pointer-to-pointer technique for the simpler traversal of linked lists? [duplicate]

This question already has answers here:
An interesting C linked list idiom
(11 answers)
Closed 5 years ago.
Ten years ago, I was shown a technique for traversing a linked list: instead of using a single pointer, you used a double pointer (pointer-to-pointer).
The technique yielded smaller, more elegant code by eliminating the need to check for certain boundary/edge cases.
Does anyone know what this technique actually is?
I think you mean double pointer as in "pointer to a pointer" which is very efficient for inserting at the end of a singly linked list or a tree structure. The idea is that you don't need a special case or a "trailing pointer" to follow your traversal pointer once you find the end (a NULL pointer). Since you can just dereference your pointer to a pointer (it points to the last node's next pointer!) to insert. Something like this:
T **p = &list_start;
while (*p) {
p = &(*p)->next;
}
*p = new T;
instead of something like this:
T *p = list_start;
if (p == NULL) {
list_start = new T;
} else {
while (p->next) {
p = p->next;
}
p->next = new T;
}
NOTE: It is also useful for making efficient removal code for a singly linked list. At any point doing *p = (*p)->next will remove the node you are "looking at" (of course you still need to clean up the node's storage).
By "double-pointer", I think you mean "pointer-to-pointer". This is useful because it allows you to eliminate special cases for either the head or tail pointers. For example, given this list:
struct node {
struct node *next;
int key;
/* ... */
};
struct node *head;
If you want to search for a node and remove it from the list, the single-pointer method would look like:
if (head->key == search_key)
{
removed = head;
head = head->next;
}
else
{
struct node *cur;
for (cur = head; cur->next != NULL; cur = cur->next)
{
if (cur->next->key == search_key)
{
removed = cur->next;
cur->next = cur->next->next;
break;
}
}
}
Whereas the pointer-to-pointer method is much simpler:
struct node **cur;
for (cur = &head; *cur != NULL; cur = &(*cur)->next)
{
if ((*cur)->key == search_key)
{
removed = *cur;
*cur = (*cur)->next;
break;
}
}
I think you mean doubly-linked lists where a node is something like:
struct Node {
(..) data // The data being stored in the node, it can be of any data type
Node *next; // A pointer to the next node; null for last node
Node *prev; // A pointer to the previous node; null for first node
}
I agree with the comments about using the STL containers for handling your list dirty work. However, this being Stack Overflow, we're all here to learn something.
Here's how you would normally insert into a list:
typedef struct _Node {
void * data;
Node * next;
} Node;
Node * insert( Node * root, void * data ) {
Node * list = root;
Node * listSave = root;
while ( list != null ) {
if ( data < list->data ) {
break;
}
listSave = list;
list = list->next;
}
Node * newNode = (Node*)malloc( sizeof(Node) );
newNode->data = data;
/* Insert at the beginning of the list */
if ( listSave == list ) {
newNode->next = list;
list = newNode;
}
/* Insert at the end of the list */
else if ( list == null ) {
listSave->next = newNode;
newNode->next = null;
list = root;
}
/* Insert at the middle of the list */
else {
listSave->next = newNode;
newNode->next = list;
list = root;
}
return list;
}
Notice all the extra checking you have to do depending on whether the insertion occurs at the beginning, end or middle of the list. Contrast this with the double pointer method:
void insert( Node ** proot, void * data ) {
Node ** plist = proot;
while ( *plist != null ) {
if ( data < (*plist)->data ) {
break;
}
plist = &(*plist)->next;
}
Node * newNode = (Node *)malloc( sizeof(Node) );
newNode->data = data;
newNode->next = *plist;
*plist = newNode;
}
As Evan Teran indicated, this works well for singly linked lists, but when it's doubly linked, you end up going through just as many if not more manipulations as the single pointer case. The other draw back is that you're going through two pointer dereferences for each traversal. While the code looks cleaner, it probably doesn't run as quickly as the single pointer code.
You probably mean a doubly-linked list, with one of the pointers going forward and the other going backward. This allows you to get to the next and previous nodes for a given node without having to remember the last one or two nodes encountered (as in a singly-linked list).
But the one thing I discovered which made the code even more elegant was to always have two dummy elements in the list at all times, the first and the last. This gets rid of the edge cases for insertion and deletion since you're always acting on a node in the middle of the list.
For example, an empty list is created:
first = new node
last = new node
first.next = last
first.prev = null
last.next = null
last.prev = first
// null <- first <-> last -> null
Obviously, traversing the list is slightly modified (forward version shown only):
curr = first.next
while curr <> last:
do something with curr
curr = curr.next
The insertions are much simpler since you don't have to concern yourself with whether you're inserting at the start or end of the list. To insert before the current point:
if curr = first:
raise error
add = new node
add.next = curr
add.prev = curr.prev
curr.prev.next = add
curr.prev = add
Deletions are also simpler, avoiding the edge cases:
if curr = first or curr = last:
raise error
curr.prev.next = curr.next
curr.next.prev = curr.prev
delete curr
All very much cleaner code and at the cost of only having to maintain two extra nodes per list, not a great burden in today's huge memory space environments.
Caveat 1: If you're doing embedded programming where space still might matter, this may not be a viable solution (though some embedded environments are also pretty grunty these days).
Caveat 2: If you're using a language that already provides linked list capabilities, it's probably better to do that rather than roll your own (other than for very specific circumstances).