Reputation: 1805
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
-------------------
Upvotes: 0
Views: 871
Reputation: 382
In the code its good to free the temp node first. Then assign the prev->next to NULL. So that it will be very easy to understand that temp node is not available, thats way making prev->next NULL.
Upvotes: 0
Reputation: 1713
As Attila already pointed out it's undefined behavior to dereference a pointer after deleting it. To prevent accidentally doing that it's good practice to assign NULL
to the pointer directly after the delete
. Dereferencing a NULL pointer immediately causes an error pointing you to the right cause.
Upvotes: 1
Reputation: 28762
delete
does not set the value of the pointer to NULL, but the memory pointed to is no longer valid (does not contain a live node
)
This means that cout << temp
will print the value of the pointer it still has (and was the address of the node before the delete
), but dereferencing temp
(e.g. *temp
or temp->next
) is undefined behavior
Note: nowehere in del
do you modify the pointer pointed to by head
, so you either don't need the double indirection (node**
) or you should assign the new head to *head
.
Upvotes: 2