Friday, 6 September 2013

Freeing memory in subroutine of recursion in C

Freeing memory in subroutine of recursion in C

I would like to ask a question about freeing memory in C. I am
implementing the mergeSort function as following:
Merge subroutine:
int* merge (int* array_left, unsigned int left_length, int* array_right,
unsigned int right_length) {
unsigned int result_size = right_length + left_length;
int* result = malloc(result_size*sizeof(int));
int r = 0; // result index
// Iterate through all left and right array elements
int i = 0; // left index
int j = 0; // right index
while ( (i < left_length) && (j < right_length) ) {
if ( *(array_left+i) < *(array_right+j) ) {
*(result+r) = *(array_left+i);
i++;
} else {
*(result+r) = *(array_right+j);
j++;
}
r++;
}
// Fill the remaining elements to the result
if (i < left_length)
while (i < left_length) {
*(result+r) = *(array_left+i);
r++;
i++;
}
if (j < right_length)
while (j < right_length) {
*(result+r) = *(array_right+j);
r++;
j++;
}
return result;
}
MergeSort:
int* mergeSort(int* array, unsigned int length) {
// Base case
if (length <= 1)
return array;
// Middle element
unsigned int middle = length / 2;
int* array_right = mergeSort(array, middle);
int* array_left = mergeSort(&array[middle], length-middle);
// Result is merge from two shorted right and left array
int* result = merge(array_left, length-middle, array_right, middle);
return result;
}
The program runs correctly but I didn't free memory from my malloc calls
and in fact I can't figure it out how to place free(). I tried to free
array_right and array_left but I got error telling me I can only free the
pointer directly allocated by malloc.
Please help! Thank you guys in advance.

No comments:

Post a Comment