Your nodes only contains a pointer and that pointer needs to point to somewhere in memory where your actual word is stored.
Maybe this example will help you understand.
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
typedef struct Node {
char *word;
struct Node *next;
} Node;
Node* newNode(char *word)
{
Node *n = malloc(sizeof(Node));
n->word = word;
n->next = NULL;
return n;
}
Node* insertNode(Node* head, Node* n)
{
n->next = head;
return n;
}
void printList(Node* head)
{
while(head)
{
printf("%s\n", head->word);
head = head->next;
}
}
int main(void) {
// Step 1: Create a list that "works" due to use of string literals
Node* head1 = NULL;
head1 = insertNode(head1, newNode("world"));
head1 = insertNode(head1, newNode("hello"));
head1 = insertNode(head1, newNode("test"));
printList(head1);
printf("------------------------------------------------\n");
// Step 2: Create a list that "fails" due to use of a char array
Node* head2 = NULL;
char str[20];
strcpy(str, "test");
head2 = insertNode(head2, newNode(str));
strcpy(str, "hello");
head2 = insertNode(head2, newNode(str));
strcpy(str, "world");
head2 = insertNode(head2, newNode(str));
printList(head2);
printf("------------------------------------------------\n");
// Step 3: Change the value that head2 nodes points to
strcpy(str, "What!!");
printList(head2);
return 0;
}
Output:
test
hello
world
------------------------------------------------
world
world
world
------------------------------------------------
What!!
What!!
What!!
Step 1:
The head1 list works as expected because each node is initialized with a pointer to a string literal which is stored somewhere in memory. Each string literal is stored in different memory. Consequently it's working fine.
Step 2:
The head2 list doesn't work as you expected. This is because each node is intialized with str so all nodes simply points to the str array. Consequently, all nodes points to "world", i.e. the last word copied into str.
Step 3:
Then a new word, i.e. "What!!" is copied into the str array and again every node will now print the contents of str, i.e. "What!!".
Conclusion:
It all depends on how you call newNode.
If you call it with a pointer to some new memory every time, you don't need to copy the word to a new location (or use strdup).
But if you reuse a buffer when calling newNode you'll need to make a copy to some other memory inside newNode (and strdup is one way to do that copy)