"Segmentation fault (core dumped)" error

why does code 1 gives segfault error whereas code 2 doesn't, both are basically same, do anyone have any suggestion?

1.
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
#include <iostream>
using namespace std;
template <class T>
class nodes
{
	template <class U> friend class linklistchain;
	private:
	nodes<T> *adrs;
	T data;
};
template <class T>
class linklistchain
{
	private:
	nodes<T> *first,*last;
	public:
	linklistchain();
	~linklistchain();
	bool isEmpty();
	bool insert(const T &x);
};
template <class T>
linklistchain<T>::linklistchain(){
last = NULL;
}
template <class T>
linklistchain<T>::~linklistchain(){
delete last;
}
template <class T>
bool linklistchain<T>::isEmpty(){
if (last)
{
	return true;
}
else
{
	return false;
}
}
template <class T>
bool linklistchain<T>::insert(const T &x)
{
isEmpty();
cout <<"ending insert";
	return true;
}
int main()
{
	linklistchain<int> *pr1;
	cout<<"started";
	pr1->insert(5);
	return 0;
}


2.
1
2
3
4
5
6
7
8
9
10
#include <iostream>
using namespace std;
int main ()
{
   int  *ptr = NULL;
   cout << "The value of ptr is " << ptr <<"\n";
        if(ptr) cout<<"ptr\n";
        if(!ptr) cout<<"not ptr\n";
   return 0;
}
both are basically same


They're not at all the same. #2 doesn't attempt to dereference an invalid pointer. #1 does.

May I know, at which step I am dereferencing it, sorry if the question is very basic. But I just am not able to figure it out.
pr1->insert(5)

pr1 points to some random place in memory. When that code is encountered it tells to compiler to interpret whatever memory pr1 is pointing to as a linklistchain<int>, and since it isn't a linklistchain<int> bad things happen.

1
2
3
4
5
6
7
int main()
{
	linklistchain<int> pr1;
	cout<<"started";
	pr1.insert(5);
	return 0;
}

thank you I missed to allocate memory
Topic archived. No new replies allowed.