Skip to content

Commit afe3d58

Browse files
Merge pull request #4922 from eholk/c6200-heuristics
C6200 heuristics
2 parents da09f4e + e462fd6 commit afe3d58

File tree

1 file changed

+26
-2
lines changed

1 file changed

+26
-2
lines changed

docs/code-quality/c6200.md

Lines changed: 26 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -8,9 +8,9 @@ ms.assetid: bbeb159b-4e97-4317-9a07-bb83cd03069a
88
---
99
# Warning C6200
1010

11-
> Index '*index*' is out of valid index range '*min*' to '*max*' for non-stack buffer '*parameter-name*'
11+
> Index '*index*' is out of valid index range '*min*' to '*max*' for nonstack buffer '*parameter-name*'
1212
13-
This warning indicates that an integer offset into the specified non-stack array exceeds the maximum bounds of that array, potentially causing random behavior and/or crashes.
13+
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.
1414

1515
## Remarks
1616

@@ -47,3 +47,27 @@ void f()
4747
delete[] buff;
4848
}
4949
```
50+
51+
## Heuristics
52+
53+
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.
54+
55+
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:
56+
57+
```cpp
58+
#include <stdlib.h>
59+
60+
void f()
61+
{
62+
int* buff = new int[14];
63+
for (int i = 1; i < 14; i++)
64+
{
65+
buff[rand()] = 0; // no warning, nothing is known about the return value of rand()
66+
buff[rand() % 15] = 0; // warning C6200, rand() % 15 is known to be in the range 0..14 and index 14 is out of bounds
67+
buff[rand() % 14] = 0; // no warning, rand() % 14 is known to be in the range 0..13
68+
}
69+
delete[] buff;
70+
}
71+
```
72+
73+
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.

0 commit comments

Comments
 (0)