Reputation: 31
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.
Upvotes: 1
Views: 122
Reputation: 16607
You allocate memory to these char *
's-
we->unique_word = malloc(sizeof(char)); // sizeof(char) is 1
....
char *s1 = malloc(sizeof(char));
Even you read one character, there is no space for '\0'
and when you pass them to strlen
, strcpy
or print them with %s
causes undefined behaviour.
You need to allocate more memory.
Note - You allocate memory in every iteration but never free
any of these. This causes memory leak .
I am not sure why
curr = head
does not modify the head when I modifycurr
That is because curr
points to head
. If you do curr=we
, curr stops pointing to head
and points to we
. This won't change head
.
Upvotes: 2
Reputation: 400
In your example, you use malloc with a sizeof(char) to allocate a char pointer (I assume?).
This is unneccessary, you don't need to allocate a char *, you need to initalize a block of memory this char pointer will point too.
What you're doing here is trying to write a block of memory into a single byte
strcpy(we->unique_word,s1);
unique_word is a pointer to a block of memory allocated of 1 byte size - you're writing out of the bounds you've allocated.
a more correct way to do it would be:
we->unique_word = (char *)malloc(strlen(s1) + 1); // For the null terminator
if (!we->unique_word) { /* Handle error where memory was not allocated */ }
strcpy(we->unique_word,s1);
Upvotes: 1