pockets
pockets

Reputation: 11

Why does delete[] throw an exception here?

I'm trying to implement the merge sort algorithm, and I can't figure out why delete[] right throws an exception :

Invalid address specified to RtlValidateHeap.

Removing the line fixes the issue, but this creates a memory leak, right? delete[] left here does not cause a problem.

void Merge(int data[], int from, int middle, int to)
{
    int leftLength = middle - from + 1;
    int rightLength = to - middle;
    
    int* left = new int[leftLength + 1];
    int* right = new int[rightLength + 1];

    for (int i = 0; i < leftLength; i++)
    {
        left[i] = data[from + i];
    }

    for (int i = 0; i < rightLength; i++)
    {
        right[i] = data[middle + i + 1];
    }

    left[leftLength] = INT_MAX;
    right[rightLength] = INT_MAX;
    
    int leftPointer = 0;
    int rightPointer = 0;

    for (int i = from; i <= to; i++)
    {
        if (left[leftPointer] < right[rightPointer])
        {
            data[i] = left[leftPointer];
            leftPointer++;
        }
        else
        {
            data[i] = right[rightPointer];
            right++;
        }
    }

    delete[] left;
    delete[] right;
}

Upvotes: 1

Views: 197

Answers (1)

MikeCAT
MikeCAT

Reputation: 75062

The pointer right is changed by the line

right++;

After executing the line, right is no longer a pointer allocated via new[] and therefore passing that to delete[] is illegal.

The line should be changed to

rightPointer++;

just like you are incrementing leftPointer instead of left in the previous line.

Upvotes: 6

Related Questions