I created a program in C which reads words from the file and stores them to a linked list but I noticed that the second continue causes undefined behavior Why is this happened?
there are 3 functions
The first function creates the list which is fine
the second function fills the list with data
the third displays the content of the list
When I ran the program is invoked to undefined behavior
FILE: https://gist.github.com/up1047388/b3018bc2a1fb0d66e86855a0d54baf63
My code :
#include<stdio.h>
#include<stdlib.h>
#include<string.h>
typedef struct node {
char str[50];
struct node *next;
}Node;
void createList(Node ** head , int len )
{ int i=0;
Node **lpp ;
Node *komvos ;
Node *komvos1;
komvos = (Node*)malloc(sizeof(Node));
komvos -> next = NULL;
lpp=&komvos;
for(i=1 ; i < len ; i++)
{
komvos1 = (Node*)malloc(sizeof(Node));
komvos1 -> next = NULL;
(*lpp) -> next = komvos1;
lpp = &(*lpp) -> next;
}
*head = komvos ;
}
void FileList(FILE *fp , Node *head)
{ char c;
char tempStr[50];
char str[50];
int i = 0 , j = 0;
Node **lpp;
lpp=&head;
for(c=fgetc(fp) ; c!=EOF ; c=fgetc(fp))
{
str[j]=c;
j++;
}
str[j]='\0';
j=0;
while(str[j]!='\0')
{
if (str[j] == ' ')
{
if (i == 0)
{
continue;
}
tempStr[i] = '\0';
i = 0;
strcpy((*lpp) -> str , tempStr);
lpp = &(*lpp) -> next ;
//continue //This continue caused the problem
}
tempStr[i] = str[j];
i++;
j++;
}
}
void printList(Node *head)
{
Node *temp;
temp = head;
for(;temp!=NULL;temp=temp->next)
{
printf("\nthe words are : %s", temp -> str);
}
}
int main ()
{
Node *head ;
head = NULL;
FILE *fp;
fp = fopen ("lists4.txt","r+");
if (fp==NULL)
{
printf("the file is broken");
exit(8);
}
createList(&head , 3);
FileList(fp,head);
printList(head);
return 0;
}