Crash when assigning value to LinkedList node

I'm trying to make my own LinkedList class, but when I try to make a node in my main function and assign it a value, my program crashes.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
//LinkedList.h
#ifndef LINKEDLIST_H
#define LINKEDLIST_H

template<typename T>

struct Node
{
	Node *next;
	T data;	
};

template<class T>

class LinkedList
{
public:
	Node<T> *m_root;
	LinkedList(Node<T> *root);
	void insert_begin(T data);
	void insert_pos(T data, const int index);
	void insert_last(T data);
	void delete_pos(const int index);
	void search(T data);
	void set(T data, const int index);
	T& operator[](const int index);

};
template<typename T>
LinkedList<T>::LinkedList(Node<T> *root)
{
	m_root->next = root->next;
	m_root->data = root->data;

}
template<typename T>
T& LinkedList<T>::operator[](const int index)
{
	Node<T> *temp;
	temp = m_root;
	int i = 0;
	while (temp != nullptr)
	{
		if (i == index)
			return temp->data;
		temp = temp->next;
		++i;
	}
}

#endif

//main.cpp
#include <iostream>
#include "LinkedList.h"

int main()
{

	Node<int> *root;
	root->data = 5; //CRASH
	root->next = nullptr;
	LinkedList<int> llist(root);
	std::cout << llist[0];
	return 0;	
}

Also, I have a question about linked lists. I have seen some examples of LinkedList classes, and all of them create their nodes within functions like insert_node(), etc. Now my question is: How is that possible? If the nodes are created within functions and not stored anywhere else, why don't they go out of scope and get destroyed?

goldenchicken wrote:
when I try to make a node in my main function and assign it a value, my program crashes.

You have not created a node. You have created a pointer to a node.

goldenchicken wrote:
If the nodes are created within functions and not stored anywhere else, why don't they go out of scope and get destroyed?

Usually they are create with new which means they will not get destroyed until delete is used.
Thanks Peter87 for the fast reply on why my program crashes!
Now I understand how it works, so thanks for that explanation too.
Topic archived. No new replies allowed.