The merge sort is written by myself

Why doesn't this code work fine? Which step do i make wrong?Code:#include <stdio.h> #include <stdlib.h> void merge(int *a, int p, int q, int r) { int n1 = q-p+1; int n2 = r-q; int *L = (int*)malloc((n1+1)*sizeof(int)); int *R = (int*)malloc((n2+1)*sizeof(int)); int i, j, k; for (i = 0; i < n1; i++) L[i] = a[p+i]; for (j = 0; j < n2; j++) R[j] = a[q+j]; L[n1+1] = -1; R[n2+1] = -1; i = 0; j = 0; for (k = p; k < r; k++) if (L[i] <= R[j]) { a[k] = L[i]; i++; } else { a[k] = R[j]; j++; } free(L); free(R); } void merge_sort(int *a, int p, int r) { if (p < r) { int q = (int)((p+r)/2); merge_sort(a, p, q); printf("asdfasd\n"); merge_sort(a, q+1, r); printf("haha\n"); merge(a, p, q, r); } } int main() { int i, n; int *a; printf("n = "); scanf("%d", &n); for (i = 0; i < n; i++) scanf("%d", &a[i]); merge_sort(a, 0, n-1); for (i = 0; i < n; i++) printf("%d ", a[i]); return 0; }