Search code examples
c++heapheapsort

Heap Sort error: Stack around variable was corrupted?


I am implementing Heap Sort for an assignment. We have to do it the same way she did in class with her pseudocode, or else we dont get credit.

Im getting a runtime error: Stack around the variable 'heapArray' was corrupted. I played with the debugger, and still was not able to figure out what is causing the error. I am pretty sure it has something to do with my For loop in the HeapSort() function. Can anyone help?

void HeapSort(int heapArray[])
{   
    int heap_size = SIZE;
    int n = SIZE;
    int temp;

    Build_Max_Heap(heapArray);//function not implemented, only declared for compile

    for(int i = n; i >=2; i--) //***I think error coming from something in here
    {
        temp = heapArray[1];
        heapArray[1] = heapArray[i];
        heapArray[i] = temp;

        heap_size = heap_size-1;
        Max_Heapify(heapArray,1);//function not implemented, only declared for compile
    }

    return;
}

int main()
{
    int heapArray[SIZE] = {  5 ,99, 32, 4, 1, 12, 15 , 8, 13, 55 };
    HeapSort(heapArray);


    cout << endl;
    return 0;
}

Solution

  • Error is:

    for(int i = n; i >=2; i--) 
    

    You have to start from n-1 since array index starts from 0. Correct way to do should be

    for(int i = n -1; i >=1; --i)
    

    array index out of bound error if you start from n. It is highly likely that pseudocode in your book (for convenience purpose) use array index from 1 to n, but in real program with C++, we should start from 0 to n-1 instead.