title: Add a node to a linked list (segmentation fault)
body: <p>The head of the linked list is input, as well as the index where the node should be added and the value associated with the node.  The program returns the head of the updated list.  If the index is greater than the size of the list, the program should return NULL.</p>
  
  <p>What is the reason for the error and how may the code be improved/optimized?</p>
  
  <pre><code>#include &lt;iostream&gt;
  
  class Node {
      public:
          int value;
          Node* next = NULL;
  };
  
  int size = 0; 
  
  Node* getNode(int data) 
  { 
      // allocating space 
      Node* newNode = new Node(); 
  
      // inserting the required data 
      newNode-&gt;value = data; 
      newNode-&gt;next = NULL; 
      return newNode; 
  } 
  
  void add(Node* head, int index, int valueInput)
  {
        if (index &lt; 1 || index &gt; size + 1) 
          std::cout &lt;&lt; "Invalid position!" &lt;&lt; std::endl;
        else { 
          // Keep looping until the pos is zero 
          while (index--) { 
  
              if (index == 0) { 
  
                  // adding Node at required position 
                  Node* temp = getNode(valueInput); 
  
                  // Making the new Node to point to  
                  // the old Node at the same position 
                  temp-&gt;next = head; 
  
                  // Changing the pointer of the Node previous  
                  // to the old Node to point to the new Node 
                  head = temp; 
              } 
              else
                // Assign double pointer variable to point to the  
                // pointer pointing to the address of next Node  
                head = (head)-&gt;next; 
          } 
          size++; 
      }
  } 
  
  void printList(struct Node* head) 
  { 
      while (head != NULL) { 
          std::cout &lt;&lt; " " &lt;&lt; head-&gt;value; 
          head = head-&gt;next; 
      } 
      std::cout &lt;&lt; std::endl; 
  } 
  
  
  int main() 
  { 
      // Creating the list 3-&gt;5-&gt;8-&gt;10 
      Node* head = NULL; 
      head = getNode(3); 
      head-&gt;next = getNode(5); 
      head-&gt;next-&gt;next = getNode(8); 
      head-&gt;next-&gt;next-&gt;next = getNode(10); 
  
      size = 4; 
  
      std::cout &lt;&lt; "Linked list before insertion: "; 
      printList(head); 
  
      int data = 12, pos = 3; 
      add(head, pos, data); 
      std::cout &lt;&lt; "Linked list after insertion of 12 at position 3: "; 
      printList(head); 
  
      // front of the linked list 
      data = 1, pos = 1; 
      add(head, pos, data); 
      std::cout &lt;&lt; "Linked list after insertion of 1 at position 1: "; 
      printList(head); 
  
      // insetion at end of the linked list 
      data = 15, pos = 7; 
      add(head, pos, data); 
      std::cout &lt;&lt; "Linked list after insertion of 15 at position 7: "; 
      printList(head); 
  
      return 0; 
  } 
  </code></pre>