Skip to content

Commit 2698ad2

Browse files
fix: Segmentation fault in merge_sort.c (#1243)
* fix segmentation fault * add a comments * add print error message when can't malloc and exit program * Update sorting/merge_sort.c Co-authored-by: Sharon "Cass" Cassidy <[email protected]> * Update sorting/merge_sort.c Co-authored-by: Sharon "Cass" Cassidy <[email protected]> --------- Co-authored-by: Sharon "Cass" Cassidy <[email protected]>
1 parent 0c5eccc commit 2698ad2

File tree

1 file changed

+20
-1
lines changed

1 file changed

+20
-1
lines changed

sorting/merge_sort.c

+20-1
Original file line numberDiff line numberDiff line change
@@ -33,6 +33,11 @@ void swap(int *a, int *b)
3333
void merge(int *a, int l, int r, int n)
3434
{
3535
int *b = (int *)malloc(n * sizeof(int)); /* dynamic memory must be freed */
36+
if (b == NULL)
37+
{
38+
printf("Can't Malloc! Please try again.");
39+
exit(EXIT_FAILURE);
40+
}
3641
int c = l;
3742
int p1, p2;
3843
p1 = l;
@@ -101,18 +106,32 @@ void merge_sort(int *a, int n, int l, int r)
101106
int main(void)
102107
{
103108
int *a, n, i;
109+
printf("Enter Array size: ");
104110
scanf("%d", &n);
111+
if (n <= 0) /* exit program if arraysize is not greater than 0 */
112+
{
113+
printf("Array size must be Greater than 0!\n");
114+
return 1;
115+
}
105116
a = (int *)malloc(n * sizeof(int));
117+
if (a == NULL) /* exit program if can't malloc memory */
118+
{
119+
printf("Can't Malloc! Please try again.");
120+
return 1;
121+
}
106122
for (i = 0; i < n; i++)
107123
{
124+
printf("Enter number[%d]: ", i);
108125
scanf("%d", &a[i]);
109126
}
110127

111128
merge_sort(a, n, 0, n - 1);
129+
printf("Sorted Array: ");
112130
for (i = 0; i < n; i++)
113131
{
114-
printf(" %d", a[i]);
132+
printf("%d ", a[i]);
115133
}
134+
printf("\n");
116135

117136
free(a);
118137

0 commit comments

Comments
 (0)