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.
So I have a function that sets a connection
void setConnection(Graph g, int sVertex, int eVertex){
ListNode *newNode = (ListNode *) malloc(sizeof(ListNode*));
newNode->vertex = eVertex;
ListNode *temp = g.list[sVertex-1];
if (temp == NULL){ // Corresponding list is empty
newNode->next = NULL;
g.list[sVertex-1] = newNode;
}
else{ // Insert new node to the front
newNode->next = temp; // set newNode's next to current 'head'
g.list[sVertex-1] = newNode; // Replace head as newNode
}
//printf("Connection set from %d to %d\n", sVertex, g.list[sVertex-1]->vertex);
return;
}
After initialization, I usually attempt to print out the adjacencyList to check if the logic is correct. The function is as follow:
void printGraphList(Graph g){
int i;
ListNode* temp;
for(i=0;i<g.V;i++)
{
printf("|");
printf("%d:\t",i+1);
temp = g.list[i];
while(temp != NULL){
printf("%d -> ",temp->vertex);
temp = temp->next;
}
printf("\n");
}
}
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
printf("%d -> ", temp->vertex);
For some reason, there are cases where the first node inserted does not have its ->next set to NULL properly. hence in the list traversal, it does not exit properly, and as such the temp->vertex is unobtainable, therefore causing the crash.
I have also debugged setConnection to ensure the links are properly set, like the actual pointer values themselves T.T
Below is an example of a working run, and a problem run. I printed an & 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->next->vertex as it does not exist...
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.