I have a program Mergesort which works with an unordered linked list.The problem I get is Segmentation Fault (core dumped).
Actually I get this error quite frequently but I do not know how to fix it. Moreover, it does not show any error or warning messages to find it. In this source code and in other case in general, I really need to know why I have this and how I fix it.
#include <stdio.h>
#include <stdlib.h>
typedef struct node_t node;
typedef struct node_t { int key; node *next; } node;
static node *head, *z;
node *merge(node *a, node *b)
{
z->next =z;
node *c = z;
do
{
if (a->key > b->key)
{
c->next = a; c = a; a = a->next;
}
else
{
c->next = b; c = b; b = b->next;
}
} while (c != z);
c = z->next;
z->next = NULL;
return c;
}
node *mergesort(node *c) {
node *a = NULL;
node *b = NULL;
if (c != NULL && c->next->next != NULL) {
a = c; b = c;
while (b->next != NULL && b->next->next != NULL) {
c = c->next;
b = b->next->next;
}
b = c->next;
c->next = NULL;
return merge(mergesort(a), mergesort(b));
}
return c;
}
void printList(node* node)
{
while (node != NULL) {
printf("%d ", node->key);
node = node->next;
}
}
node *listcreate(int n, node *a)
{
node *head = NULL;
node *temp = NULL;
node *p = NULL;
int i=0;
while(i<n)
{
temp = (node*) malloc(sizeof(node*));
printf("Please insert the number: ");
scanf("%d", &(temp->key));
temp->next = NULL;
if(head == NULL)
head = temp;
else
{
p = head;
while(p->next != NULL)
p = p->next;
p->next = temp;
}
i++;
}
a = head;
}
int main()
{
node *a = NULL;
listcreate(3, a);
a = mergesort(a);
printf("Sorted Linked List is: \n");
printList(a);
getchar();
return 0;
}