Error implementing linked list in C

I have a program written in C. And I'm struggling with an effect that I cannot understand. An application reads a sequence of words as command line input. When reading an input, it puts one word into the list. Then prints the list. Which makes me think, why the values โ€‹โ€‹added by the user, the loop prints correctly, while the values โ€‹โ€‹added inside the loop are not. I mean, what values โ€‹โ€‹are entered by the user, only the last will be printed. And besides, it will be printed as many times as the number of values โ€‹โ€‹is entered. The two main suspects are the push and printList methods:

void push(struct List * list, char* newValue){
    assert(list != NULL);
    assert(newValue != NULL);

    Node* node = createNode();
    node->data = newValue;
    node->next = NULL;
    if(list->firstNode != NULL){
        node->next = list->firstNode;
        list->firstNode = node;
    }
    else list->firstNode = node;
}

void printList(struct List * list){
    assert(list != NULL);
    Node *node = list->firstNode;
    while(node->next != NULL){
        printf("%s ", node->data);
        node = node->next;
    }
    if(node != NULL) printf("%s ", node->data);
}

But I could not find mistakes there. What I have done is comparing the behavior with and without a while loop:

int main(){
    struct List* list = createList();
    char s[256];
    int a;
    push(list, "he");
    push(list, "bee");
    push(list, "gee");
    while(scanf("%s", &s) == 1) push(list, s);
    printList(list);
}

The result obtained:

c c c gee bee he

:

a b c

,

c b a gee bee he

? .

P.S. defs , :

typedef struct Node {
    char* data;
    struct Node *next;
} Node;

typedef struct List {
    struct Node *firstNode;
} List;

Node *createNode(){
    Node* node = malloc(sizeof(struct Node));
    assert(node != NULL);

    node->data = "";
    node->next = NULL;
    return node;
}

List *createList(){
    List* list = malloc(sizeof(struct List));
    list->firstNode = NULL;
    assert(list != NULL);
    return list;
}
+4
2
while(scanf("%s", &s) == 1) push(list, s);

, push, s . , , , , , .

, s "c". node s, "c" , node.

+5

data , . . - :

node->data = strdup(newValue);

strdup, , .

if(list->firstNode != NULL){
    node->next = list->firstNode;
    list->firstNode = node;
}
else list->firstNode = node;

if(list->firstNode != NULL){
    node->next = list->firstNode;
}
list->firstNode = node;

node->next = list->firstNode;
list->firstNode = node;

: , node->next NULL createNode . . . createNode. node->data NULL . .

+3

Source: https://habr.com/ru/post/1687285/


All Articles