The following routine is expected to remove the node at the start of a single linked list but it fails sometimes.
void remove_from_front(node *start)
{
delete start;
start = start->link;
print_list(start);
}
Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.
Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.
Lost your password? Please enter your email address. You will receive a link and will create a new password via email.
Please briefly explain why you feel this question should be reported.
Please briefly explain why you feel this answer should be reported.
Please briefly explain why you feel this user should be reported.
There are few problems I can see:
You are freeing the
startnode and then accessing the freed memory. This is incorrect, it leads to undefined behavior which means anything can happen. In one run it might work and in the next run it might crash.Your function needs to make changes to the head of the list but it is not making the changes visible to the called function as it is not returning anything and the argument
startis passed by value. To fix this either pass the address or reference of thestartpointer.Your function might be called on an empty list,
start = NULL. You need to handle that case.Correct implementation: