It all boils down to the following sequence:
struct ListN* newn = (struct ListN*)malloc(sizeof(struct ListN));
newn->value = 1;
newn= newn->next;
newn->value = 2;
The first two statements create a new element and set its data value but do not set its "next element" pointer to anything.
The third statement sets newn
to the arbitrary value stored in the next
pointer of the first element, and the fourth dereferences that to try and set its value.
This (dereferencing an arbitrary pointer) is undefined behaviour, pure and simple. At that point, literally anything is allowed to happen.
If you're looking to construct a two-element list, the following is a more correct way to do it:
struct ListN* newn = (struct ListN*)malloc(sizeof(struct ListN));
newn->value = 1;
newn->next = (struct ListN*)malloc(sizeof(struct ListN));
newn= newn->next;
newn->value = 2;
newn->next = NULL;
Though you should really take into account:
- that you would be better off using
new
rather than malloc
in C++;
- that, if you do use
malloc
, you should check for failure; and
- C++ (from C++11 onwards) already has a singly-linked list in its repertoire,
forward_list
. You should probably just use that unless your intent is to learn algorithms. Before C++11, you could just use list
, though this is a doubly-linked list.