I\'ve written this function:
List* delPaintingCode(List* head, char *code)
{
List *p,*q;
for(p=head;p!=NULL;q=p,p=p->next)
{
if(!strc
The logical problem that leads to a crash is in the if (p==head)
branch of your code: when you delete the initial element, you free the head
without updating p
. This leads to dereferencing a freed pointer on the very next iteration.
You can fix the problem by introducing a fake node with head
in its next
, and returning the next
, like this:
List fake;
fake.next = head;
// This loop always looks ahead by one element, i.e. at p->next.
for(List *p = &fake ; p->next != NULL ; p = p->next) {
if(strcmp(code, p->next->code)) {
continue;
}
List *q = p->next;
p->next = q->next;
free(q);
}
return fake.next;
This approach works for the initial element, too, because we added a fake head to our list, so the first time around p->next
is the same as head. This lets us unify treatment of head element and all other elements.