Hey,

Long time reader, first time poster. I'm working on a project, and think that I have the logic correct, but I think that my code may have some memory errors. I'm not asking for you to give me any asnwers, but a little help in the right direction would be greatly appreciated.

void merge(void *keys, int l, int mid, int r, int size, int (*compare) (const void *, const void *))
{
	char *temp =(char*)malloc((l+r)*size);
	char *pkeys = (char*)keys;
	int j, k;
	//i = l;
	j = mid + 1;
	k = 0;

	while(l <= mid && j <= r) {
	//for (i = 0, k = 0, j = mid; i < mid && j < n;){
		if(compare(&pkeys[j*size], &pkeys[l*size]) < 0) {
			temp[k] = pkeys[l];
			l++;
		}
		else {
			temp[k] = pkeys[j];
            j++;
		}
		k++;
	} 
	//if(l > mid) {
		while (j <= r) {
			temp[k] = pkeys[j];
			k++;
			j++;
		}
	//}
	//else {
		while (l <= mid) {
			temp[k] = pkeys[l];
			k++;
			l++;
		}
	//}
 
	/* Copy temp back */
	for (int i = l; i <= r; i++) {
		pkeys[i] = temp[i];			
	}
}

void mrg_sort(void *keys, int l, int r, int size, int (*compare) (const void *, const void *))
{
	int mid;
	if(l < r) {
		mid = (l+r)/2;
		mrg_sort(keys, l, mid, size, compare);
		mrg_sort(keys, (mid+1), r, size, compare);
		merge(keys, l, mid, r, size, compare);
	}
}

void rms_sort(void *keys, int n, int size, int (*compare) (const void *, const void *))
{
	char *pkeys = (char *)keys;
	mrg_sort(pkeys, 0, (n-1), size, compare);
}

Thanks

Q1 are you learning C or C++?

> char *temp =(char*)malloc((l+r)*size);
You don't call free(temp) at the end.
Also, if you start at 3 and end at 5, how many slots in the array do you need? Surely it's not 8

You're also modifying l in your code, and you seem to need that later on.

BTW, an identifier of lower-case-L is very hard to read.

This article has been dead for over six months. Start a new discussion instead.