title: LinkedList Traversal crashing randomly
body: <p>I am working on a Graph problem, so my program has an initialization which sets all connection using an adjacencyList. Currently encountering a really weird bug and was wondering if anyone could give some insights as to what may be happening.</p>
  <p>So I have a function that sets a connection</p>
  <pre><code>void setConnection(Graph g, int sVertex, int eVertex){
      ListNode *newNode = (ListNode *) malloc(sizeof(ListNode*));
      newNode-&gt;vertex = eVertex;
  
      ListNode *temp = g.list[sVertex-1];
  
      if (temp == NULL){ // Corresponding list is empty
          newNode-&gt;next = NULL;
          g.list[sVertex-1] = newNode;
      }
      else{ // Insert new node to the front
          newNode-&gt;next = temp; // set newNode's next to current 'head'
          g.list[sVertex-1] = newNode; // Replace head as newNode
      }
  
  
      //printf(&quot;Connection set from %d to %d\n&quot;, sVertex, g.list[sVertex-1]-&gt;vertex);
      return;
  }
  </code></pre>
  <p>After initialization, I usually attempt to print out the adjacencyList to check if the logic is correct. The function is as follow:</p>
  <pre><code>void printGraphList(Graph g){
      int i;
      ListNode* temp;
  
      for(i=0;i&lt;g.V;i++)
      {
          printf(&quot;|&quot;);
          printf(&quot;%d:\t&quot;,i+1);
          temp = g.list[i];
          while(temp != NULL){
              printf(&quot;%d -&gt; &quot;,temp-&gt;vertex);
              temp = temp-&gt;next;
          }
          printf(&quot;\n&quot;);
      }
  }
  </code></pre>
  <p>So here's the weird part, the code works fine most of the time, but occasionally crashes randomly when printing the adjancencyList. I debugged it down to</p>
  <pre><code>printf(&quot;%d -&gt; &quot;, temp-&gt;vertex);
  </code></pre>
  <p>For some reason, there are cases where the first node inserted does not have its -&gt;next set to NULL properly. hence in the list traversal, it does not exit properly, and as such the temp-&gt;vertex is unobtainable, therefore causing the crash.</p>
  <p>I have also debugged setConnection to ensure the links are properly set, like the actual pointer values themselves T.T</p>
  <p>Below is an example of a working run, and a problem run. I printed an &amp; before printing the vertex and and @ after. As shown in the image, for vertex 7, it should be linked to only vertex 9 and 10, but in the problem run, it looks like the node for 9's next is not set to NULL properly, causing the program to crash in attempt to get node 9's-&gt;next-&gt;vertex as it does not exist...</p>
  <p>As mentioned before, this happens once every 3 to 4 runs and i have no clue whats causing this inconsistency. Any help is appreciated! Thanks in advance.</p>
  <p><a href="https://i.stack.imgur.com/A8Sni.png" rel="nofollow noreferrer">Problem Example</a>
  <a href="https://i.stack.imgur.com/cmhZq.png" rel="nofollow noreferrer">Working Example</a></p>