-3

Fairly new, the code output is as follows:

1->2->exit

However, program fails to execute completely, (even though this is the end of program, spooky)

Here is the code:

struct ListN{
int value;
ListN* next;
};

int main()
{
struct ListN* newn = (struct ListN*)malloc(sizeof(struct ListN));
newn->value = 1;

struct ListN* temp;
temp = newn;

newn= newn->next;

newn->value = 2;
newn->next = NULL;

while(temp!=NULL){
    printf("%d ->",temp->value);
    temp = temp->next;
}
printf("exit");
return 0;
}
ivan_pozdeev
  • 33,874
  • 19
  • 107
  • 152
pranavhd
  • 25
  • 7
  • 5
    Are you *sure* you're really programming C++? You only use *one* C++-specific feature (unless there's a `typedef` you don't show us), and you use it only *once* even though you could do it in multiple places. – Some programmer dude Dec 29 '17 at 09:52
  • 1
    As for your problem, `newn= newn->next;` is probably not what you want to do, and will lead to *undefined behavior* in the very next statement. – Some programmer dude Dec 29 '17 at 09:53
  • 1
    `malloc`? You claim it’s C++! –  Dec 29 '17 at 09:53
  • https://www.programiz.com/cpp-programming/library-function/cstdlib/malloc This link showed malloc in C++ also, and this answered why i shouldnt use malloc https://stackoverflow.com/questions/184537/in-what-cases-do-i-use-malloc-vs-new Thanks, learned – pranavhd Dec 29 '17 at 20:13

1 Answers1

0

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.
paxdiablo
  • 854,327
  • 234
  • 1,573
  • 1,953
  • Thank you!.. Coming back to C/C++ after a very long time, thus some basic concept flaws. Your answer helps thanks – pranavhd Dec 29 '17 at 20:09