I have a program in c which receives messages from different clients and servers. When the messages come in it adds the message to that list. After the message is added to the list I print it on the screen and on the other servers. But i want to delete the node that contains the message after it is printed so when the the print function gets called only prints the new messages. How can I delete the node after print?
Here is my struct:
typedef struct trade_list {
char* trader_msg;
u_int32_t id_of_sender;
int sender_timer;
int local_time;
struct trade_list *next;
}trade_list;
trade_list *head = NULL;
And here is how I print:
void print_trades()
{
trade_list * newnode = head;
trade_list *previous = NULL;
while (newnode) {
previous = newnode;
if ((elapsed - newnode->local_time >= 8))
printf ("%s\n", newnode->trader_msg);
newnode = newnode->next;
if (previous == NULL)
head = newnode->next;
else
{
previous->next = newnode->next;
free(newnode);
}
}
}
Thus gives me a segmentation fault. I tried changing the newnode->next to just newnode in the else part. previous->next = new node; It didn’t give me an error but it did not erase the node as it kept printing that node every time the print function was called
At the start of your function:
At each iteration in your loop, before
newnode = newnode->next;addprev = newnode.Then to delete:
Fairly simple.
EDIT: You should really have some functions like
list_create,list_add,list_removeassociated with your data structure, rather than just chucking like the remove code into a print function. That’s the first thing I do when I create any sort of data structure.Another option is to have your linked list like:
EDIT2: As for your edit, change
print_tradesto something like:In your code,
previouswill never beNULLsince you set it tonewnodeat the start of the loop, andnewnodealso shouldn’t equalnewnode->nextuntil afternewnodehas been processed completely. You’re also usingnewnodeafter you’vefreed it.