I have a file with a double-linked-list that contains a set of process identifiers and some state information.
struct pr7_process
{
pid_t pid; /* process ID, supplied from fork() */
/* if 0, this entry is currently not in use */
int state; /* process state, your own definition */
int exit_status; /* supplied from wait() if process has finished */
struct pr7_process *next; // a pointer to the next process
struct pr7_process *prev;
};
/* the process list */
struct process_list
{
struct pr7_process *head;
struct pr7_process *tail;
};
I have a method to remove an element of my list:
{
struct pr7_process *cur;
for(cur = list->head; cur != NULL; cur = cur->next)
{
if (cur->pid == pid)
{
printf("cur pid: %d\n", cur->pid);
cur->state = STATE_NONE;
if(list->head == list->tail)
{
free(cur);
}
else
{
cur->prev->next = cur->next;
cur->next->prev = cur->prev;
free(cur);
}
break;
}
}
}
What is wrong with my remove function? I seem to get an infinite loop when I try to print my list. Previously I thought it was the way I used free() but apparently not from the replies 🙂
Thanks!
When you add a node set
nexttoNULL.Then when you free all, free until next == NULL.
When you remove a node. Update links and free node.
Also; free on NULL is an noop.
Valgrind is a invaluable tool when working on such things.
Believe you have to do some more checks; I.e.:
Given that you build the list something like i.e.: