title: Segmentation fault using doubly linked list in C
body: <p>I've written an implementation of a doubly linked list with a .h prototype here and everything runs fine until I start entering values in the terminal. I get a segmentation fault after entering the second value, but, if I just use 1 value it executes normally. I've gone through it several times, but, I can't find my mistake. Could you guys help me find why I'm getting the error?</p>
  
  <p>Here's the .h file: </p>
  
  <pre><code>#include &lt;stdio.h&gt;
  typedef struct node Node;
  
  struct node
  {
      int d;
      Node *link;
  }*head,*current,*prev;
  
  int num_nodes;
  
  void linked_list_init(int data);
  void linked_list_sort();
  void linked_list_print();
  </code></pre>
  
  <p>And here's the .c file:</p>
  
  <pre><code>#include "link.h"
  #include &lt;stdio.h&gt;
  #include &lt;malloc.h&gt;
  #include &lt;stdlib.h&gt;
  
  void main(){
  
      int n,e,i;
      printf("How many numbers do you want to sort: ");
      scanf("%d",&amp;e);
      for(i=0;i&lt;e;i++){
          printf("Enter number: ");
          scanf("%d",&amp;n);
          linked_list_init(n);
      }
      linked_list_sort();
      printf("The sorted numbers are: ");
      linked_list_print();
  }
  
  void linked_list_init(int data){
      Node *prev=0,*next=0;
  
      current=(Node*)malloc(sizeof(Node));    
      if(head==0)
      {
          head=current;
          current-&gt;d=data;
          current-&gt;link=0;
          prev=current;
  
      }
      else{
          current-&gt;d=data;
          current-&gt;link=0;
          prev-&gt;link=current;
          prev=current;
      }
      }
  
  void linked_list_sort(){
      int i,j;
      Node *prev=0,*next=0;
  
      current=head;
      prev=head;
      next=head-&gt;link;
  
      for(i=0;i&lt;num_nodes-1;i++)
      {
          for(j=0;j&lt;num_nodes-i-1;j++)
          {
              if(current-&gt;d&gt;next-&gt;d)
              {
                  current-&gt;link=next-&gt;link;
                  next-&gt;link=current;
                  if(current==head)
                  {
                      head=next;prev=next;
                  }
                  else
                  {
                      prev-&gt;link=next;prev=next;
                  }
                  if(next!=0) //check whether final node is reached
                      next=current-&gt;link;
  
              }
              else //move each node pointer by one position
              {
                  prev=current;
                  current=next;
                  next=current-&gt;link;
              }
  
          }
          //next iteration
          current=head;
          prev=head;
          next=current-&gt;link;
      }
  
  }
  
  void linked_list_print(){
      current=head;
      while(current!=0){
          printf("%d ",current-&gt;d);
          current=current-&gt;link;
      }
  }
  </code></pre>