i have this loop which is suppose to delete all nodes from the list and then free the memory that they occupy. could somebody check what is wrong with it. im kinda lost here. thanks in advance
Code:for (p=first; p!=NULL; p=p->next) free(p);
This is a discussion on linked list problem within the C Programming forums, part of the General Programming Boards category; i have this loop which is suppose to delete all nodes from the list and then free the memory that ...
i have this loop which is suppose to delete all nodes from the list and then free the memory that they occupy. could somebody check what is wrong with it. im kinda lost here. thanks in advance
Code:for (p=first; p!=NULL; p=p->next) free(p);
You are freeing p and then the for loop has to do a p=p->next operation. How can you say p=p->next when p is gone? A possible solution is to use a temp pointer:
Code:for (p=first; p!=NULL; ) { node* temp = p->next; // Use whatever pointer type needed in place of 'node' free(p); p = temp; }
I used to be an adventurer like you... then I took an arrow to the knee.