C/Segmentation fault in the following code
Expert: Narendra - 6/7/2004
QuestionIn the following code I have a linked list pointed to by pointer "head". For every node in this list (pointed to by "q"), I will traverse the entire list( using pointer "p") putting in the values "link-weight" if the distance between nodes is less than R.
This function gives a segmentation fault at the end. It works fine and I get that "q" is NULL but i think it does not exit the outer while loop correctly. Any answers to why segmentation fault occurs?
void Make_Topology(struct node *head){
struct adj_node *new;
struct node *q = head;
struct node *p;
int link_wt;
while(q != NULL){
printf("%d\n", q->id);
p = head;
while (p!=NULL){
printf(" The orig node is %d\t and this node is %d\n", q->id, p->id);
if (p!=q && dist(q,p) <= R)
{
q->Nneigh++;
if (q->adj == NULL)
{
q->adj = (struct adj_node *)malloc(sizeof(struct adj_node));
q->adj->id = p->id;
printf(" Enter the link weight between node %d and node %d \n", q->id, p->id);
q->adj->link_wt = scanf("%d", &link_wt);
q->adj->next = NULL;
}
else
{
new = (struct adj_node *)malloc(sizeof(struct adj_node));
new->id = p->id;
printf(" Enter the link weight between node %d and node %d \n", q->id, p->id);
new ->link_wt = scanf("%d", &link_wt);
new ->next = q->adj;
q->adj = new;
}
}
p=p->next;
}
q = q->next;
}
AnswerWithout looking at the complete code, it is difficult to analyze.
Looking at the code segment that you have posted and the comments that you have made regarding the crash, this is what I think is the problem:
In the while loop (It goes on till p becomes NULL):
Before p becomes NULL, q is becoming NULL.
And loop is executed again and in the end, you are making:
q = q->next;
Since q is already NULL, q->next cannot be accessed and is making the code to crash!
-ssnkumar