Skip to content

Commit 7e2e845

Browse files
committed
Document some heuristics around out of bounds indices
1 parent 23999fe commit 7e2e845

File tree

1 file changed

+24
-0
lines changed

1 file changed

+24
-0
lines changed

docs/code-quality/c6200.md

Lines changed: 24 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -47,3 +47,27 @@ void f()
4747
delete[] buff;
4848
}
4949
```
50+
51+
## Heuristics
52+
53+
Code analysis cannot always prove whether an array index is in range. This can be particularly true when the index is computed from a complex expression, including those that use 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 which uses `rand()` in index calculations as a standin for a function call that code analysis cannot 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 does not warn with just `rand()` because it does not 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)