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

1.

#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.

#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;
}

For some reason, I am able to run the first program without any issues whatsoever, which absolutely baffles me because looking at it, it probably should crash. You create a pointer called pr1 which is supposed to point to a linkedlistchain, but you never initialize it nor set it to point to anything. Your insert() function calls the isEmpty() function, which in turn reads memory that doesn't belong to your program, crashing it. That's my best guess.

The reason your second program runs without any issues if obvious. You can read the value of ptr no matter what it is, whether it's NULL or pointing to valid memory. If you try to write to that address or dereference it, that's when you start to get problems if it doesn't point somewhere valid. Adding the following line to your second program will probably cause it to crash:

cout << "The value of *ptr is" << *ptr << endl;

Edited 3 Years Ago by Tumlee

This question has already been answered. Start a new discussion instead.