[Solved] Insert linked list


In your Insert function, you never allocate newNode.

Node* newNode;

You need to allocate it like so:

Node* newNode = new Node();

The program runs correctly after fixing this, and the output is:

24

http://ideone.com/16XL5W

EDIT:
Regarding your comment below, the following lines do not allocate anything:

Node* newNode;
struct Node* newNode;

They are simply declaring variables, because you have identified them as pointers (*). Pointers simply point to an object on the heap. In order to actually create an object on the heap, you need to use new Node().

The reason your program crashed is because you were trying to access memory from a pointer that hadn’t been initialized.

You can use malloc if you want, but you’re programming in C++, so as a general rule, never use malloc unless you actually need to.

If you are using a compliant compiler, use shared_ptrs, then you never have to worry about deleteing things that you new.

7

solved Insert linked list