head updates on each insertion while converting text file to singly linked list in C

As the question specifies I want to convert a text file into linked list. When I read the string elements from an array it works fine but while doing the same from file creates the issue of updated head. The following is what I've tried...


//creating structure
typedef struct node {
    char *word;
    struct node *next;

//function for creating a node
node *createnode(char *wrd){
    node *temp1;
    temp1 = (node*)malloc(sizeof(node));
    temp1->word = wrd;
    temp1->next = NULL;
    return temp1;

//function for creating and adding new node to linked list
node *creat(node *head, char *wrd){
    node *temp, *p;
    temp = createnode(wrd);
    if(head == NULL){
        head = temp;
        p = head;
        while(p->next != NULL){
            p = p->next;
        p->next = temp;

        printf("p->word from creat method: %s ADDR: %p HEAD: %s \n", p->word, 
    return head;

//traverse the list and display each node
node *show(node *head){
    node *p;
    while(p != NULL){
        printf("from show method: %s", p->word);
        p = p->next;

int main()
     node *head = NULL;
     /* Character array to read the content of file */
     char sWord[20];
     /* Pointer to the file */
     FILE *fp;

     /* Opening a file in r mode*/
     fp= fopen ("hw10data.txt", "r");

     while( fscanf(fp, "%s", sWord) != EOF )
        head = creat(head, sWord); //create list

     return 0;

I don't know why the head is updating on each insert. Any help will be appreciated.

1 answer

  • answered 2018-04-17 06:03 Stephan Lechner

    It's not the head of the list which is changing; it's just that you read in the values into a local array sWord, which you then pass to the creat and createnode-functions. Therein, you simply assign a pointer, but you do not copy the content of sWord; Hence, all node contents will point to the same memory address, i.e. to sWord; and when you read in new values, all node contents will point to that new value. So it just seems as if the "head" has changed. Actually all nodes will show the same content...

    To overcome this, write the following in createnode:

    // temp1->word = wrd;
    temp1->word = strdup(wrd);

    Or, if strdup is not available:

    temp1->word = malloc(strlen(wrd)+1);