,C, Crash while try to delete last element in a list -


my program's aim delete elements numeric value. program works fine, except when should delete last element: makes program crash.

i have created list structure:

struct elemento{        int dato;        struct elemento *next; }; 

you can ignore how list created, since know error in function:

struct elemento *eliminapari(struct elemento *p){     struct elemento * start = p;    struct elemento * temp, *temp2;    int cont;    cont = 0;    temp2 = p;    while(p != null && cont != 20){          temp2 = temp2->next;           if((p->dato % 2) == 0){              if (cont == 0){ //if first element                  start = p->next;                 free(p);                 p = start;               }else if(p->next == null){ //if last element                 temp2->next = null; //this previous node                 free(p);                 p = null;               }else{                 temp = p->next;                 p->dato = p->next->dato;                 p->next = p->next->next;                 free(temp);               }          }else{printf("\n3\n"); p = p->next;}         cont = cont + 1;      }         return(start);     } 

thanks.

go through happen if call eliminapari passing p struct instance (in other words, p->next null. first line inside while loop sets temp2 == null. in "else" clauses try dereference temp2 (temp2->next = null), temp2 null, crash.


Comments

Popular posts from this blog

javascript - Bootstrap Popover: iOS Safari strange behaviour -

Magento/PHP - Get phones on all members in a customer group -

session - Logging Out Using PHP -