Search code examples
c++mergesortdynamic-arrays

Heap corruption error when deleting array


I am attempting to read in a text file containing a list of random numbers and ordering them using mergesort to display. The numbers are read in to a dynamic array. Unfortunately, a heap corruption error is detected whenever I attempt to delete arrays that are not in use.

Mergesort Function:

void mergesort(int *arr, int first, int last)
{
if(first < last)
   {
   int middle = ((first + last)/2);
   mergesort(arr, first, middle);
   mergesort(arr, middle+1, last);
   merge(arr, first, last); 
   }
}

Error occurs in Merge Function when I delete tempArr:

void merge(int *arr, int first, int last)
{
int *tempArr = new int[last];

int mid = (first+last)/2;
int first1 = first;
int last1 = mid;
int first2 = mid + 1;
int last2 = last;

int index = first1;

for(; (first1 <= last1) && (first2 <= last2); ++index)
{
    if (arr[first1] < arr[first2])
    {
        tempArr[index] = arr[first1];
        ++first1;
    }
    else
    {
        tempArr[index] = arr[first2];
        ++first2;
    }
}

for(; first1 <= last1; ++first1, ++index)
    tempArr[index] = arr[first1];

for(; first2 <= last2; ++first2, ++index)
    tempArr[index] = arr[first2];

for(index=first;index<=last;++index)
    arr[index] = tempArr[index];

delete [] tempArr;
}

Solution

  • The problem seems to be that you allocate your array as int *tempArr = new int[last]. The number of its elements is last and their indices are 0, 1, ... last - 1.

    Near the end of the function, you have this:

    for(; first2 <= last2; ++first2, ++index)
        tempArr[index] = arr[first2];
    

    last2 is initialised to the value of last. This means the final assignment in the loop will be when index == last, so you're accessing tempArr[last]. That's out of array bounds.