BnE
BnE

Reputation: 61

Why does calling delete on a dynamically allocated array cause one to crash but not the other?

I am working on a function that'll do merge sorting. I have a working merge function but I am having some problems with my split function. The function split takes a single int array and it's size and then splits that array into two smaller arrays. My issue is, I don't know why calling delete [] on tempArrayL causes a crash but when I do so on tempArrayR it does not.

void split(int x[], int size)
{

    if (size == 1)
    return;

    //figure out sizes of smaller arrays
    int leftSize = (size / 2), rightSize = (size - leftSize), mid = (leftSize + 1);


    int* tempArrayL = new int[leftSize]; //array for first half
    for (int z = 0; z != mid; z++)
    {
        tempArrayL[z] = x[z]; //copy from original into new array
    }

    for (int z = 0; z != leftSize; z++)
       cout << tempArrayL[z] << endl; //print out to see if it worked


    int* tempArrayR = new int[rightSize]; //array for second half
    for (int z = mid - 1, j = 0; z != size; j++, z++)
    {
        tempArrayR[j] = x[z]; //copy from original array
    }
    for (int z = 0; z != rightSize; z++)
    cout << tempArrayR[z] << endl; //print out to see if it worked


    delete [] tempArrayL; //causes crash here
    delete [] tempArrayR; //does not cause crash if I comment out tempArrayL

}

Here is how it maybe used in main

int main()
{
    const int SIZE = 5;
    int array[] = {3, 2, 5, 9, 10};
    split(array, SIZE);
} 

Upvotes: 0

Views: 106

Answers (1)

Shankha057
Shankha057

Reputation: 1371

So basically as @Bo Persson mentioned in his comment. You are accessing elements that are out of bounds. Your tempArrayL is allocated size of 2 elements(meaning only index {0,1}) But in the first loop(where you copy elements into the left array), your loop condition is z!=mid and your mid is 3 which meant that you are accessing indices {0,1,2} and your tempArrayL can have indices {0,1} only. Hence, index out of bounds.

Long story short: Replace for (int z = 0; z != mid; z++)
With for (int z = 0; z !=leftSize; z++)
in the very first loop of the split(int[] x,int size) method(where you copy elements into the left array)

Upvotes: 2

Related Questions