Reputation: 364
I'm working on a linked list program, and am trying to remove the last item. I've attempted the function down below, but it's faulty and leads to a seg fault.
I've got a struct as such in a header file:
struct test{
char * name;
char * type;
struct test * next;
};
And I've got a function in a separate .c file, as such:
//NOTE Correct memory is allocated in other parts of the program
//(i.e not in this function)
//Also values are initialized in other functions...etc
test * removeLastItem(test * head)
{
test * parent, * cursor;
if(head == NULL) //if list is empty return NULL
{
return NULL;
}
else
{
while(cursor->next != NULL) //untill last item of the list is found..
{
parent = cursor; //parent equal to current element
cursor = cursor->next; //current element set to next pointer of current element
}
parent->next = NULL; //parent next pointer is now null
}
return head; //return the head of the list
}
I'm not exactly sure if my implication is correct here, but I'm required to return the head of the list, which I do believe I'm doing. Any help would be much appreciated.
Upvotes: 0
Views: 511
Reputation: 225262
cursor
. free()
call in here somewhere.Upvotes: 1