adding text from file to a linked list
i am trying to add words from a text file to a linked list. my code works fine , but if the text file is too big it shows the following error: stack smashing detected. Can anyone help me please here is my code
Code:
#include <stdlib.h>
#include <string.h>
#include <time.h>
#include <stdio.h>
FILE *f;
int wordc=-1;
struct list {
char *str;
struct list *next;
};
struct list *root;
struct list *head;
struct list *curr=NULL;
int init_list(){
root=(struct list *)malloc(sizeof(struct list));
head=root;
if(root==NULL ){
printf("Init list failed\n");
return(1);
}
root[0].next=NULL;
return(0);
}
int list_add(char string[],int wordc){
struct list *curr=(struct list *)malloc(sizeof(struct list));
char *str1;
if(root==NULL ){
printf("Add list failed\n");
return(1);
}
str1= (char *)malloc(60*sizeof(char));
strcpy(str1,string);
curr->str=str1;
if(wordc==0)
head->next=curr;
else
root->next=curr;
curr->next=NULL;
root=curr;
}
void print_list(){
struct list *ptr;
ptr=head;
while(ptr!=NULL){
printf("|%s|\n", ptr->str);
ptr=ptr->next;
}
printf("\n");
}
int open_file(char fname[]){
FILE *f;
char ch;
char buf[60];
int i=0;
f=fopen(fname,"r");
if ( f== NULL ){
printf("ERROR OPENING THE FILE\n");
return(1);
}
//word count
do
{
if((ch=fgetc(f))==EOF)
break;
do{
buf[i]=ch;
i++;
}while((ch=fgetc(f))!='\n');
buf[i]='\0';
wordc++;
printf("1\n");
list_add(buf,wordc++);
i=0;
printf("2\n");
}while(1);
}
int main(int argc,char *argv[]){
if(argc!=2){
printf("wrong parameters\n");
return(1);
}
init_list();
open_file(argv[1]);
print_list();
}