title: Fixing Segmentation Fault Sometimes in C
body: <p>I am a beginner of learning c, and segmentation happens many times for me. I also did some research online about segmentation fault: some reasons are allocate memory problems, null pointer, or memory access problem. But I am confused that why sometimes the code work, but sometimes it says segmentation fault? Below is the code I am getting this issue in both the <code>insertAt</code> and <code>destroyList</code> functions:</p>
  
  <pre><code>#include &lt;stdio.h&gt;
  #include &lt;stdlib.h&gt;
  
  typedef struct NODE{
      int data;
      struct NODE* next;
  } node;
  
  node* insertAt(node*, int, int);
  void printList(node*);
  void destroyList(node*);
  
  node* myList;
  int counter = -1;
  
  int main()
  {
      myList = NULL;
      int pos, input;
  
      myList = insertAt(myList, 0, 333);
      myList = insertAt(myList, 0, 555);
      myList = insertAt(myList, 1, 222);
      myList = insertAt(myList, 3, 444);
  
      printf("My List:\n");
      printList(myList);
  
      destroyList(myList);
  
      printf("After Destroy:\n");
      printList(myList);
  
      return 0;
  }
  
  node* insertAt(node* head, int pos, int newData)
  {
      node* temp = (node*) malloc(sizeof(node));
      temp-&gt;data = newData;
      counter++;
  
      if(head == NULL){
          head = temp;
          return head;
  
      }else if (pos == 0)
      {
          temp-&gt;next = head;
          head = temp;
          return head;
  
      }else if(head != NULL &amp;&amp; pos &gt; counter){
          node* current = head;
          node* temp2 = current;
          while(current != NULL){
              temp2 = current;
              current = current-&gt;next;
          }
          temp-&gt;next = current;
          temp2-&gt;next = temp;
          return head;
  
      }else
      {
          node* current = head;
          while(pos-1&gt;0){
              current = current-&gt;next;
              pos--;
          }
          temp-&gt;next = current-&gt;next;
          current-&gt;next = temp;
          return head;
      }
  }
  
  void printList(node* head)
  {
      node* ptr = head;
  
      while (ptr != NULL)  {
          printf("%i ", ptr-&gt;data);
          ptr = ptr-&gt;next;
      }
      printf("\n");
  }
  
  void destroyList()
  {
      node* temp;
      while(myList){
          temp = myList;
          myList = temp-&gt;next;
          free(temp);
      }
  }
  </code></pre>