Why do I get a segmentation fault while calculating the one's complement of a binary number?
<p>I have written a C++ code to store a binary number using a doubly linked list where the LSB is stored in the head node.</p>

<p>Whenever I enter '0' in the head node I get a segmentation fault while calculating the one's complement, however I do not have this problem when I enter '1' in the head node.</p>

<p>My code:</p>

<pre><code>#include&lt;iostream&gt;
using namespace std;

class node
{
 int bin;
 node *prev,*next;
 public:
  node(int b)
  {
   bin=b;
   prev=NULL;
   next=NULL;
  }
 friend class II;
};

class II
{
 node *head,*tail;
 int digits;
 public:
  II()
  {
   head=NULL;
   tail=NULL;
  }

 void dig()
 {  
  cout&lt;&lt;"Enter the number of digits: ";
  cin&gt;&gt;digits;
  if(digits&lt;2)
  {
   cout&lt;&lt;"Please enter more digits: ";
   cin&gt;&gt;digits;
  }
  else{}
 }

 void create()
 {
  int y;
  if(head==NULL)
  {
   node *q;
   cout&lt;&lt;"Enter binary digit: ";
   cin&gt;&gt;y;
   if(y&lt;0||y&gt;1)
   {
    cout&lt;&lt;"Enter again: ";
    cin&gt;&gt;y;
   }
   q=new node(y);
   head=q;
   head-&gt;next=NULL;
   head-&gt;prev=NULL;
  }
  else
  {
   cout&lt;&lt;"ll created";
  }
 }

 void insert()
 {
  node* temp=head;
  node* q;
  int i,y;
  i=1;
  while(i&lt;digits)
  {
   cout&lt;&lt;"Enter the next digit";
   cin&gt;&gt;y;
   if(y&lt;0||y&gt;1)
   {
    cout&lt;&lt;"Please enter again: ";
    cin&gt;&gt;y;
   }
   else
   {
    q=new node(y);
    temp-&gt;next=q;
    q-&gt;next=NULL;
    q-&gt;prev=temp;
    tail=q;
    temp=temp-&gt;next;
    i++;
   }
  }
 }

 void disp()
 {
  node *temp=tail;
  while(temp!=NULL)
  {
   cout&lt;&lt;temp-&gt;bin;
   temp=temp-&gt;prev;
  }
  cout&lt;&lt;endl;
 } 

 void neg()
 {
  node *temp=tail;
  while(temp!=NULL)
  {
   if(temp-&gt;bin==0)
   {  
    cout&lt;&lt;"1";
    temp=temp-&gt;prev;
   }  
   if(temp-&gt;bin==1)
   {  
    cout&lt;&lt;"0";
    temp=temp-&gt;prev;                                                                                           
   }
  }
  cout&lt;&lt;endl;
 }  
};

int main()
{
 II a;
 a.dig();
 a.create();
 a.insert();
 a.disp();
 a.neg();
 return 0;
} 
</code></pre>

<p>Output:</p>

<pre><code>Enter the number of digits: 4
Enter binary digit: 1
Enter the next digit1
Enter the next digit0
Enter the next digit0
0011
1100
</code></pre>

<p>And:</p>

<pre><code>Enter the number of digits: 4
Enter binary digit: 0
Enter the next digit0
Enter the next digit1
Enter the next digit1
1100
Segmentation fault (core dumped)
</code></pre>

<p>Why is this happening?</p>