Επεξεργασία

Κοινή χρήση μέσω


Warning C6201

Index 'index-name' is out of valid index range 'minimum' to 'maximum' for possibly stack allocated buffer 'variable'

This warning indicates that an integer offset into the specified stack array exceeds the maximum bounds of that array. It might potentially cause stack overflow errors, undefined behavior, or crashes.

Remarks

One common cause of this defect is using an array's size as an index into the array. Because C/C++ array indexing is zero-based, the maximum legal index into an array is one less than the number of array elements.

Code analysis name: INDEX_EXCEEDS_MAX

Example

The following code generates warning C6201. The for loop condition exceeds the valid index range for buff when it sets i to 14, which is one element past the end:

void f()
{
    int buff[14]; // array of 0..13 elements
    for (int i = 0; i <= 14; i++) // i == 14 exceeds the bounds
    {
        buff[i] = 0; // initialize buffer
    }
}

To correct the warning, make sure the index stays in bounds. The following code shows the corrected loop condition:

void f()
{
    int buff[14]; // array of 0..13 elements
    for (int i = 0; i < 14; i++) // i == 13 on the final iteration
    {
        buff[i]= 0; // initialize buffer
    }
}

Heuristics

This analysis is limited to stack-allocated arrays. It doesn't consider, for example, arrays passed into the function with a Microsoft source code annotation language (SAL)-annotated length.

This analysis can't catch all possible out of bounds indices because not all arithmetic can be precisely analyzed. It's tuned to report cases where it can guarantee an out of bounds index is possible. The absence of a warning doesn't mean the index is guaranteed to be in bounds.