title: Weird segmentation fault that disappears on using cout
body: <p>I'm trying out a basic program that will randomly initialize a linked list and print the value at a user-specified index (getnth). However, I'm running into a weird segmentation fault that appears when I comment out a specific cout line, and disappears when I uncomment it.</p>
  
  <pre><code>#include&lt;iostream&gt;
  #include&lt;cstdlib&gt;
  
  using namespace std;
  
  struct node
  {
      int x;
  node *next;
  };
  
  void ins(struct node*&amp; headRef, int n)
  {
      node *newNode = new node;
  if (!newNode)
      return;
  newNode-&gt;x = n;
  if (!headRef)
      newNode-&gt;next = NULL;
  else
      newNode-&gt;next = headRef;
  headRef = newNode;
  cout&lt;&lt;"\n"&lt;&lt;n&lt;&lt;" inserted at "&lt;&lt;headRef&lt;&lt;"\n\n";
  }
  
  void disp(struct node* head)
  {
      node *temp = head;
      if (!temp)
  {
      cout&lt;&lt;"\n\nLL empty\n";
      return;
  }
  while (temp)
  {
      cout&lt;&lt;temp-&gt;x&lt;&lt;" ";
      temp = temp-&gt;next;
  }
  cout&lt;&lt;"\n\n";
  }
  
  void getnth(struct node* head, int n)
  {
  int i=0;
  node *temp = head;
  while (temp)
  {
      if (i == n)
      {
          cout&lt;&lt;"\n"&lt;&lt;temp-&gt;x&lt;&lt;"\n\n";
          return;
      }
  }
  
  cout&lt;&lt;"\nIndex too high\n";
  }
  
  int main()
  {
  node *head;
  int i;
  
  srand(time(NULL));
  for (i=0; i&lt;10; i++)
  {
      ins(head, rand()%10+1);
      cout&lt;&lt;"Main head is "&lt;&lt;head&lt;&lt;"\n"; // segfault appears if this line is commented out, disappears if it's not
  }
  
  cout&lt;&lt;"\nInitial LL\n\n";
  disp(head);
  cout&lt;&lt;"\nEnter index ";
  cin&gt;&gt;i;
  getnth(head, i);
  return 0;
  }
  </code></pre>