From 2698ad2d135142bcfee9d43a41dba14c28309c5c Mon Sep 17 00:00:00 2001 From: Pongsakorn TIPPAYASOMDECH Date: Sun, 9 Apr 2023 08:58:03 +0700 Subject: [PATCH] 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 * Update sorting/merge_sort.c Co-authored-by: Sharon "Cass" Cassidy --------- Co-authored-by: Sharon "Cass" Cassidy --- sorting/merge_sort.c | 21 ++++++++++++++++++++- 1 file changed, 20 insertions(+), 1 deletion(-) diff --git a/sorting/merge_sort.c b/sorting/merge_sort.c index c61767a1..ac1046f4 100644 --- a/sorting/merge_sort.c +++ b/sorting/merge_sort.c @@ -33,6 +33,11 @@ void swap(int *a, int *b) void merge(int *a, int l, int r, int n) { int *b = (int *)malloc(n * sizeof(int)); /* dynamic memory must be freed */ + if (b == NULL) + { + printf("Can't Malloc! Please try again."); + exit(EXIT_FAILURE); + } int c = l; int p1, p2; p1 = l; @@ -101,18 +106,32 @@ void merge_sort(int *a, int n, int l, int r) int main(void) { int *a, n, i; + printf("Enter Array size: "); scanf("%d", &n); + if (n <= 0) /* exit program if arraysize is not greater than 0 */ + { + printf("Array size must be Greater than 0!\n"); + return 1; + } a = (int *)malloc(n * sizeof(int)); + if (a == NULL) /* exit program if can't malloc memory */ + { + printf("Can't Malloc! Please try again."); + return 1; + } for (i = 0; i < n; i++) { + printf("Enter number[%d]: ", i); scanf("%d", &a[i]); } merge_sort(a, n, 0, n - 1); + printf("Sorted Array: "); for (i = 0; i < n; i++) { - printf(" %d", a[i]); + printf("%d ", a[i]); } + printf("\n"); free(a);