0

I want to read the words of a file into a linked list. The file contains two words: cat & caterpillar.

However, the output of my linked list just spits out caterpillar twice. Something somewhere is wrong. Can someone please help.

------CODE-----    
#include <stdio.h>
#include <stdlib.h>
#include <string.h>

typedef struct node
{
    char* word;
    struct node* next;
}
node;  

int main (int argc, char* argv[])
{        
    char *dictfile = argv[1];

    FILE* dict = fopen(dictfile, "r");     //opens the file which contains two words, cat & caterpillar

    if (dict == NULL)
        return 1;

    node* head = NULL;       

    char* oneword = malloc(sizeof(node));  

    while ((fgets (oneword, 24, dict)) != NULL)
    {                                        
        node* temp = (node*)malloc(sizeof(node));            
        temp->word = oneword;

        printf("%s\n", temp->word);     //prints the word for debug sake

        temp->next = head;            
        head = temp;             
    }

    node* temp = (node*)malloc(sizeof(node));
    temp = head;

    while(temp != 0)    //loop to print the linked list
    {           
        printf("traverse %s\n", temp->word);    /prefix'ing traverse to know its from linked list
        temp = temp->next;
    }

    printf("SUCCESS!!\n");      

}    

When I run the program, this is what happens:

-----RESULT-----
./tempeol small checksmall
cat

caterpillar

traverse caterpillar

traverse caterpillar

SUCCESS!!
2

So the problem relates to your char* oneword variable.

You have one chunk of memory for all your char*s and with every loop your fgets function overwrites the old data with the new word.

So conceptually what you probably want to do, is on each iteration create a new chunk of memory and copy the data from oneword into that new chunk and then have your node point to this new chunk instead of to oneword.

If you take this approach, remember you don't want oneword to exist in memory after this functional call, so consider stack vs heap and if you decide to keep it in the heap make sure to free it.

One last point consider what size your string should be to avoid buffer overflow or wasted space.

Hope that helps!

4
  • Thanks Antoine. But still not working. I've saved the new code here: gist.github.com/0aa5923e15cb9e10ab02
    – jzz
    Mar 20 '15 at 17:07
  • tempword = oneword; -> this line copies pointer not the data. You want to look at functions strcpy(). Mar 20 '15 at 17:15
  • strcpy(tempword, oneword);??? :)
    – jzz
    Mar 20 '15 at 17:20
  • Antione, you're awesome! DID IT, finally!! I realise I cannot copy a char* directly. After I used strcpy(), I was getting a weird output so I changed fgetc() to fscanf() to just read the words instead of the whole line. Phew! After 48 hours of sleeplessness, its done. Thanks again.
    – jzz
    Mar 20 '15 at 17:34

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .