Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How come I can still access nodes after deleting an entire linked list?

Following is a function for deleting the entire list by accessing the head pointer to the 1st node:

void deleteList(Node *head)
{
  while (head != nullptr)
  {
    Node *temp = head;
    head = head->next;
    delete temp;
  }
}

Detailed program:

struct Node {
  int data;
  Node* next;
};

void traverseList(Node* head) {
  while (head != nullptr) {
    cout << head->data << endl;
    head = head->next;
  }
}

void deleteList(Node *head)
{
  while (head != nullptr)
  {
    Node *temp = head;
    head = head->next;
    delete temp;
  }
}

int main() {
  Node* head = new Node();
  head->data = 10;
  head->next = new Node();
  head->next->data = 20;
  head->next->next = new Node();
  head->next->next->data = 30;

  traverseList(head);// traversing list before deletion
  deleteList(head);
  traverseList(head);// traversing list after deletion
}

Even after deleting the list, the program can access the list again, how is that possible?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

Is there any other way to delete the list?

Is the delete keyword working properly? Or, do we not know how to delete the node and how the delete keyword works?

>Solution :

Even after deleting the list, the program can access the list again, how is that possible?

Deleting an object invalidates any pointer that is pointing at it. Accessing an object through an invalid pointer results in undefined behaviour. When the behaviour of the program is undefined, "anything" is possible. You should avoid having undefined behaviour in your program. Refrain from attempting to access memory through invalid pointers.

Is the delete keyword working properly?

Yes.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading