Warning C6200

Index 'index' is out of valid index range 'min' to 'max' for nonstack buffer 'parameter-name'

This warning indicates that an integer offset into the specified nonstack array exceeds the maximum bounds of that array, causing undefined behavior and potentially crashes.

Remarks

One common cause of this defect is using the size of an array 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_NONSTACK

Example

The following code generates this warning. This issue stems from the for loop exceeding the index range, attempting to access index 14 (the 15th element) when index 13 (the 14th element) is the last:

void f()
{
    int* buff = new int[14]; // array of 0..13 elements
    for (int i = 0; i <= 14; i++) // i exceeds the index
    {
        buff[i] = 0; // warning C6200
    }
    delete[] buff;
}

To correct both warnings, use correct array size as shown in the following code:

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

Heuristics

Code analysis can't always prove whether an array index is in range. This can happen, for example, when the index is computed from a complex expression, including those expressions that call into other functions. In these cases, code analysis may fall back on other clues to determine the range an array index expression may fall into.

For example, consider the following function that uses rand() in index calculations as a stand-in for a function call that code analysis can't analyze:

#include <stdlib.h>

void f()
{
    int* buff = new int[14];
    for (int i = 1; i < 14; i++)
    {
        buff[rand()] = 0;       // no warning, nothing is known about the return value of rand()
        buff[rand() % 15] = 0;  // warning C6200, rand() % 15 is known to be in the range 0..14 and index 14 is out of bounds
        buff[rand() % 14] = 0;  // no warning, rand() % 14 is known to be in the range 0..13
    }
    delete[] buff;
}

Code analysis doesn't warn with just rand() because it doesn't have any information about its return value. On the other hand, rand() % 15 and rand() % 14 provide hints as to the range of the return value of rand() and code analysis can use that information to determine that the index is out of bounds in the first case but not the second.