The following code is a single linked list implementation in c. every time the function addtoqueue
is being called, it creates a node and appends the node to the end of the list. The pointer list points to the first node of the linked list, but every time I update the value of node using input (the values are read from client connection), all the previous nodes in the linked list gets the last filename that has been inputed. i.e:
after 1st node creation (abc.txt as input): linked list has one node with value abc.txt;
after 2nd node (xyz.txt as input): linked list has two nodes with same filename xyz.txt.(instead of one node with abc and one node with xyz)
There's my implementation below, what end where is the logical failure?
struct listdata
{
char *filename;
struct listdata *next;
}*list;
void addtoqueue(int client,char *value)
{
char buffer[512];
char filepath[100];
struct listdata *temp,*input;
input=(struct listdata *)malloc(sizeof(struct listdata));
read(client,buffer,sizeof(buffer));
d = sscanf(buffer,"%s",filepath);
input->filename=&filepath;
if(list == NULL)
{
list=input;
list->next=NULL;
}
else if((list->next)==NULL)
{
list->next=input;
input->next=NULL;
}
else
{
temp=list->next;
while((temp->next)!=NULL)
{
temp=temp->next;
}
temp->next=input;
input->next=NULL;
}
//list points to the first node
}
This is simpler
void addtoqueue(int client,char *value)
{
char buffer[512];
char filepath[100];
struct listdata *temp=NULL,*input=NULL;
input=(struct listdata *)malloc(sizeof(struct listdata));
read(client,buffer,sizeof(buffer));
d=sscanf(buffer,"%s",filepath);
input->filename=&filepath;
input->next = NULL;
if(list == NULL)
{
list=input;
}
else
{
temp=list;
while(temp->next != NULL)
{
temp=temp->next;
}
temp->next=input;
}
}
Collected from the Internet
Please contact [email protected] to delete if infringement.
Comments