0

```
#include <stdio.h>
#include <malloc.h>
struct node {
int data;
struct node *link;
};
void append (int data, struct node **s) {
struct node *p, *q;
if (*s == NULL) {
p = (struct node *) malloc (sizeof (struct node));
p->data = data;
p->link = NULL;
*s = p;
return;
}
q = *s;
p = (*s)->link;
while (p != NULL) {
q = p;
p = p->link;
}
q->link = (struct node *) malloc (sizeof (struct node));
q->link->data = data;
q->link->link = NULL;
return;
}
void insertion_sort (struct node *s) {
int i, j;
struct node *temp = s, *r;
for (i = 0; temp != NULL; i++, temp = temp->link)
;
int n = i;
for (i = 0; i < n; i++) {
r = s->link;
for (j = i + 1; j < n ; j++) {
if (s->data > r->data) {
int temp = s->data;
s->data = r->data;
r->data = temp;
}
r = r->link;
}
s = s->link;
}
}
void display (struct node *p) {
while (p != NULL) {
printf("%d ", p->data);
p = p->link;
}
printf("\n");
}
main() {
struct node *list1, *list2;
append (56, &list1);
append (45, &list1);
append (99, &list1);
append (23, &list1);
append (54, &list1);
display(list1);
insertion_sort(list1);
display(list1);
append (44, &list2);
append (12, &list2);
append (57, &list2);
append (76, &list2);
append (89, &list2);
display(list2);
insertion_sort(list2);
display(list2);
}
```

If I comment from where I start appending list2 in the main function, the code works fine for list1 and the list sorts properly.

I'm getting error "Segmentation fault(core dumped)" if I append numbers to list2.

Please someone explain me why I'm getting error when I'm making list2 ?

This code works fine:

```
#include <stdio.h>
#include <malloc.h>
struct node {
int data;
struct node *link;
};
void append (int data, struct node **s) {
struct node *p, *q;
if (*s == NULL) {
p = (struct node *) malloc (sizeof (struct node));
p->data = data;
p->link = NULL;
*s = p;
return;
}
q = *s;
p = (*s)->link;
while (p != NULL) {
q = p;
p = p->link;
}
q->link = (struct node *) malloc (sizeof (struct node));
q->link->data = data;
q->link->link = NULL;
return;
}
void insertion_sort (struct node *s) {
int i, j;
struct node *temp = s, *r;
for (i = 0; temp != NULL; i++, temp = temp->link)
;
int n = i;
for (i = 0; i < n; i++) {
r = s->link;
for (j = i + 1; j < n ; j++) {
if (s->data > r->data) {
int temp = s->data;
s->data = r->data;
r->data = temp;
}
r = r->link;
}
s = s->link;
}
}
void display (struct node *p) {
while (p != NULL) {
printf("%d ", p->data);
p = p->link;
}
printf("\n");
}
main() {
struct node *list1, *list2;
append (56, &list1);
append (45, &list1);
append (99, &list1);
append (23, &list1);
append (54, &list1);
display(list1);
insertion_sort(list1);
display(list1);
/* append (44, &list2);
append (12, &list2);
append (57, &list2);
append (76, &list2);
append (89, &list2);
display(list2);
insertion_sort(list2);
display(list2); */
}
```

*Edited 4 Years Ago by prakhs*