struct fifo
{
int result;
char *info;
struct fifo *next;
}*node;
void add(struct fifo **n,int data,char *text)
{
struct fifo *temp,*node1;
if (*n==NULL)
{
temp=(struct fifo *)malloc(sizeof(struct fifo));
printf("%d is to be stored\n",data);
temp->result=data;
printf("%d is stored\n",temp->result);
temp->info=(char *)malloc(strlen(text)+1);
strcpy(temp->info,text);
temp->next=NULL;
*n=temp;
}
else
{
temp=*n;
while(temp->next!=NULL)
temp=temp->next;
node1=(struct fifo *)malloc(sizeof(struct fifo));
node1->result=data;
node1->info=(char *)malloc(strlen(text)+1);
strcpy(node1->info,text);
node1->next=NULL;
temp->next=node1;
}
}
void del(struct fifo **n)
{
struct fifo *temp;
if (*n==NULL)
{
printf("Linked list is empty\n");
}
else
{
temp=*n;
*n=temp->next;
}
}
//Inside read thread that will add to the linked list
//If a particular condition is satisfied
EnterCriticalSection(&critical);
add(&node,50,location); //location holds the string read
LeaveCriticalSection(&critical); //exit condition after this
//Inside main thread that reads & deletes from the linked list
InitializeCriticalSection(&critical);
while(1)
{
if (node==NULL)
{
printf("Nothing to read\n");
Sleep(4000);
}
else
{
EnterCriticalSection(&critical);
temp=(struct fifo *)malloc(sizeof(struct fifo));
printf("%d\n%s\n",node->result,node->info);
op=node->result;
printf("op is %d\n",op);
detail=(char *) malloc (strlen(node->info));
strcpy(detail,node->info);
printf("%s\n",detail);
del(&node);
LeaveCriticalSection(&critical);
if (node==NULL)
printf("node is null\n");
else
printf("node is not null\n");
if (op==50)
{
//call function with detail as parameter...call is successful
free(detail);
Sleep(2000);
//Make some other function calls
op=-1;
if (node==NULL)
printf("%d\n",op);
else
printf("node is not null\n");
printf("%d\n",op);
}
//some other similar conditions
}
DeleteCriticalSection(&critical);
//Close threads
return (0);
//End of main
Now, there are no errors in compilation. When I read something, main thread reads that & deletes the node. I get a confirmation of the same due to the printf given after the del(&node). Then, i go into my function calls, which give the right result. But at the end of it I get an error & my printf statement shows that on the 2nd check node is not null.
To make things clear this is how the output looks like:
Nothing to read
//after some time
50 //value of int stored in node
25 //string stored in node
op is 50
25
node is null
//results of function calls successfully printed
node is not null
-1
Please tell me what is wrong with the above code.