I am using a linked list which i named word_entry. The struct for the word_entry is the following:
struct word_entry
{
char *unique_word ;
int word_count ;
struct word_entry *next;
struct word_entry *prev;
} ;
And this is how I am using the code:
struct word_entry *head = NULL;
struct word_entry *curr = NULL;
int read_file( char *file_name )
{
int initialized = 0;//was head initialized?
char ch;
FILE *file;
struct word_entry *we = malloc(sizeof(struct word_entry));
we->unique_word = malloc(sizeof(char));
we->prev = NULL;
we->next = NULL;
char *s1 = malloc(sizeof(char));
char *s2 = s1;
file = fopen(file_name, "r");//opens the file
if(!file){
return 0;//file not opened
}else{
while((ch = fgetc(file))!= EOF){
if(ch >= 'A' && ch <= 'z'){
*s2++ = ch;
continue;
}
if(strlen(s1)>0){
if(!initialized){
head = malloc(sizeof(struct word_entry));
curr = head;
initialized = 1;
}
*s2 = '\0';
strcpy(we->unique_word,s1);
we->word_count = 1;
curr = we;
printf("%s\n", head->unique_word);
s1 = malloc(sizeof(char));
s2 = s1;
}
}
return 1;
}
return 0; //file not opened
}
I am not sure why curr = head does not modify the head when I modify curr. I would like help on figuring out to how implement my code so that whenever i modify curr it also modifies the information in head.
we->unique_word = malloc(sizeof(char));) is worrying; only one byte allocated, and the string not null terminated. Similarly withchar *s1 = malloc(sizeof(char));. Your loop starts invoking undefined behaviour on the second iteration ass2steps beyond the end of the space allocated fors1. You're in a world of hurt from there onwards.