Errors C++

HEAP CORRUPTION DETECTED: before Normal block - Example 2

If you make an array of 3, for example, and then try to write data to the element at index 3 (one index past the last item in the array), such as this:

#include <iostream>

int main() {

    double* dpArray = new double[3];
    dpArray[0] = 3.2;
    dpArray[1] = 4.5;
    dpArray[2] = 10.2;

    dpArray[3] = 11.3;

    delete [] dpArray;

    std::cin.get();

    return 0;
}

When you run this program in Debug mode (menu Debug -> Start Debugging), you will receive this error:

This error is a little more helpful; it says that you may have a bug in your program. What it doesn't tell you is that, in this case, it's because you tried to access a memory location outside of the valid array. The 3rd index of the array is outside of the array, whose indices only go from 0 to 2 (i.e., an array size of 3).

To fix this, make sure not to go past the largest index in your array. This type of problem can easily happen in a for or while loop while incrementing the index and not having a valid upper bound.

 

© 2007–2024 XoaX.net LLC. All rights reserved.