Reputation:
This is part of my code.
while(1)
{
struct client* newnode = malloc(sizeof(client));
if(head->next != NULL)
{
newnode = newnode -> next;
}
if(head->next == NULL)
{
newnode->next = head->next;
head->next=newnode;
}
ReadEOF = fscanf(fp1,"%d %s %s %s %s\n",&(newnode->ID),newnode->PW,newnode->NAME,newnode->ADDRESS,newnode->PNUM);
if((ReadEOF)!= 5)
{
break;
}
++NumofClient;
printf("%d",NumofClient);
} //make newnodes
These codes are written before loop.
struct client* head=malloc(sizeof(client));
head->next = NULL;
int NumofClient = 0;
int ReadEOF;
This is struct client.
typedef struct client{
int ID;
char PW[100],NAME[100],ADDRESS[100],PNUM[100];
struct client* next;
}client;
This is client.txt file.
123 aa aa aa aa aa
234 bb bb bb bb bb
567 cc cc cc cc cc
I expected the value of NumofClient as 3.
but I found program goes out from the loop when the value of NumofClient is 1.
It means fscanf funtion`s return value was not 5 at 2nd attempt.
Or, are there any error occurred during the linked list implementation?
If you need , I will gladly write the full code in comment
Upvotes: 1
Views: 68
Reputation: 41036
You are overwritting (memory leak) and assigning garbage (non initialized value) to the new node in:
if(head->next != NULL)
{
newnode = newnode -> next;
}
I think you want
newnode->next = head;
head = newnode;
Upvotes: 1