I am trying creating a circular link list. When I try to add an element by passing the head pointer as a reference, it throws a segmentation fault. I noticed that the value of the head pointer is changing as soon as I call the Add element function. Code snippet:
struct Node {
int data;
struct Node *next;
};
int c = 1;
typedef struct Node node;
//node *head = NULL, *temp, *temp2, *z;
node *InitQueue(node *);
node *AddQueue(node *, int);
void DelQueue();
void display(node *);
void main()
{
int ch;
node *head = NULL;
do {
printf("1.Creation Q\n");
printf("2.Insert element to Q\n");
printf("3.Delete element\n");
printf("4.Display Q\n");
printf("5.Exit\n");
printf("Enter your choice:\n");
scanf("%d", &ch);
switch (ch) {
case 1:
head = InitQueue(&head);
printf("%d %p\n", head->data, head->next);
break;
case 2:
printf("%d %p\n", head->data, head);
int item;
printf("Enter item\n");
scanf("%d", &item);
head = AddQueue(&head, item);
break;
case 3:
DelQueue();
break;
case 4:
display(&head);
break;
case 5:
exit(0);
}
} while (ch != 5);
}
node *InitQueue(node * head)
{
node *temp;
temp = (node *) malloc(sizeof(node));
printf("%p \n", temp);
temp->next = temp;
head = temp;
printf("%p \n", head->next);
return head;
}
node *AddQueue(node * head, int item)
{
//InitQueue(&head);
printf("%d %p\n", head->data, head);
node *temp, *temp2;
temp = head;
temp2 = (node *) malloc(sizeof(node));
//printf("Enter the data: \n");
//scanf("%d", &temp2->data);
temp2->data = item;
while (temp->next != head) {
temp = temp->next;
}
temp->next = temp2;
temp->next = head;
head = temp2;
return head;
}