Most of code works but when I try to delete last element of my list and I print it I see in its place some garbage data, what I'm doing wrong here? Could somebody point my mistake?
void DeleteClient2(struct client *temp,struct client **head)
{ struct client *prev=*head;
struct client *current = *head;
struct item *currentitem = (*head)->item_data,*save;
if(temp== *head)
{
while(currentitem != NULL)
{
save = currentitem;
currentitem = currentitem ->next;
free(save);
}
free(temp);
temp->item_data = NULL;
(*head) = (*head)->next;
}
else
if(temp->next == NULL)
{
while(currentitem != NULL)
{
save = currentitem;
currentitem = currentitem ->next;
free(save);
}
temp->item_data = NULL;
free(temp);
}
else
if(temp != *head && temp->next != NULL)
{
while(prev->next != temp)
{
prev=prev->next;
}
prev->next = temp->next;
while(currentitem != NULL)
{
save = currentitem;
currentitem = currentitem ->next;
free(save);
}
temp->item_data = NULL;
free(temp);
temp=temp->next;
}
}
Code:
free(temp);
temp=temp->next; // temp->next is invalid
Is undefined behaviour, Once you free a node you can't access it, doing so is illegal.
Here you check that *head == temp and if yes, you free temp ie *head cause they equal, you just verified it, and than you say (*head) = (*head)->next; which set *head to garbage most probably
if(temp== *head)
{
while(currentitem != NULL)
{
save = currentitem;
currentitem = currentitem ->next;
free(save);
}
free(temp);
temp->item_data = NULL;
(*head) = (*head)->next;
}
Same mess is here
temp->item_data = NULL;
free(temp);
temp=temp->next;
void DeleteClient2(struct client *temp,struct client **head)
{ struct client *prev=*head;
struct client *current = *head;
struct item *currentitem = (*head)->item_data,*save;
if(temp== *head) \\ if head is the node to be deleted
{
while(currentitem != NULL)
{
save = currentitem;
*head = currentitem->next;
\\ currentitem = currentitem ->next;
free(save);
}
}
else
if(temp->next == NULL) \\ if the node to be deleted is last node then
{
while(currentitem->next != NULL)
{
*prev = currentitem;
currentitem = currentitem ->next;
}
prev->next = NULL;
free(currentitem);
}
else
if(temp != *head && temp->next != NULL)\\ node to be deleted is between head and last node
{while(prev->next != temp)
{ currentitem = *prev;
prev=prev->next;
}
currentitem->next = temp->next;
free(temp);
\\while(currentitem != NULL)
\\ {
\\ save = currentitem;
\\ currentitem = currentitem ->next;
\\\ free(save);
\\ }
\\ temp->item_data = NULL;
\\ free(temp);
\\ temp=temp->next;
}
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.