Why does adding a new value to a linked list overwrite the existing content? : <p>I'm trying to add randomly generated values into a linked list using a for loop. When I try to print the list out, it has the correct number of entries, but they all match the values of the last item that was entered. </p>

<p>Here is the code.</p>

<pre><code>#include &lt;stdio.h&gt;
#include &lt;stdlib.h&gt;
#include &lt;time.h&gt;

typedef struct student {
    int num;
    char* name;
} student;

typedef struct container {
    student* data;
    struct container* next;
} container ;

container* front;
container* back;

container* createContainer(student* data) {

    container* tmp = malloc(sizeof(container));

    tmp-&gt;data = data;
    tmp-&gt;next = NULL;

    return tmp;

}

int add(student* to_add) {

    printf("%d %s\n", to_add-&gt;num, to_add-&gt;name);

    back-&gt;next = createContainer(to_add);
    back = back-&gt;next;


    return 1;
}

void printList(container* front) {

    container* tmp = front;

    int i;
    i=0;
    while (tmp != NULL) {
        i++;
        printf("%d:\t%d\t\t%s\n", i, tmp-&gt;data-&gt;num, tmp-&gt;data-&gt;name);
        tmp = tmp-&gt;next;
    }

}

int main(void) {
    srand(time(NULL));

    student st = {rand(), "test"};
    front = createContainer(&amp;st);
    back = front;

    printList(front);

    int i;
    for (i=0; i&lt;12; i++) {
        st.num = rand();
        st.name = "test";
        add(&amp;st);
    }

    printList(front);

    // print the third value stored in the list.
    container* tmp = front-&gt;next-&gt;next;
    printf("%d\t\t%s\n", tmp-&gt;data-&gt;num, tmp-&gt;data-&gt;name);

    return EXIT_SUCCESS;
}
</code></pre>

<p>Here is what it outputs:</p>

<pre><code>1:  25312       test
17285 test
3447 test
8299 test
14310 test
22628 test
31306 test
8682 test
31936 test
18951 test
4107 test
7910 test
20556 test
1:  20556       test
2:  20556       test
3:  20556       test
4:  20556       test
5:  20556       test
6:  20556       test
7:  20556       test
8:  20556       test
9:  20556       test
10: 20556       test
11: 20556       test
12: 20556       test
13: 20556       test
20556       test
</code></pre>

<p>The first line shows that the first value is added correctly. The non-numbered lines are what the values in the list should be, and the numbered lines show the values actually stored in the list. The last line is just printing the third value stored in the list, just to show that it is (hopefully) not a problem with the print function. </p>
