I coded the following. Insert, delete at beginning, insert at beginning and end are all working fine. The memory marked in bold is not freed up. Should cout<<temp give an error? Please comment on the correctness of this code.
void del(node** head)
{
node* temp = (*head)->next;
node* prev = *head;
while(temp ->next!= NULL)
{
prev = temp;
temp = temp -> next;
}
cout<<endl<<temp;
cout<<endl<<prev;
//delete prev ->next;
prev -> next = 0;
delete temp;
cout<<endl<<"temp after free"<<temp;
cout<<endl<<prev;
}
void main()
{
node* head = NULL;
int x = 5;
head = insert(head,x);
insert(head,6);
insert(head,7);
insert(head,8);
print(head);
del(&head);
print(head);
getch(); }
Output:
Empty List
|5| at 00673BF0
-------------------
|6| at 00673C30
-------------------
|7| at 00673FB8
-------------------
|8| at 00673FF8
-------------------
00673FF8
00673FB8
temp after free00673FF8
00673FB8
|5| at 00673BF0
-------------------
|6| at 00673C30
-------------------
|7| at 00673FB8
-------------------
deletedoes not set the value of the pointer to NULL, but the memory pointed to is no longer valid (does not contain a livenode)This means that
cout << tempwill print the value of the pointer it still has (and was the address of the node before thedelete), but dereferencingtemp(e.g.*temportemp->next) is undefined behaviorNote: nowehere in
deldo you modify the pointer pointed to byhead, so you either don’t need the double indirection (node**) or you should assign the new head to*head.