Reputation: 13
I have a problem with the function below, when (*ptr)
is NULL instead of ending the while loop the function crashes. I've tried to use if((*ptr)->next==NULL) break;
but it fails anyway.
boolean search_times(struct list ** ptr, float *V, int n, struct list_times ** new ){
struct list * tmp_ptr=NULL;
if( V!=NULL && n>=0 ) {
while((*ptr)!=NULL) {
int times=0;
for (int i = 0; i < n; i++) {
if (isequal((*ptr)->value, V[i]))
times++;
}
if((suf_insert_times(new, (*ptr)->value, times))==FALSE)
return FALSE;
tmp_ptr=*ptr;
ptr=&(*ptr)->next;
free(tmp_ptr);
}
return TRUE;
}
else
return FALSE;
}
Upvotes: 1
Views: 64
Reputation: 9804
ptr=&(*ptr)->next;
saves a pointer to the member next
of an object, which is freed in the next line. Trying to dereference ptr
in the next iteration will lead to undefined behaviour.
*ptr = (*ptr)->next;
should be correct. This will advance the list to the next item, while the previous one will be freed in the next line.
Upvotes: 1