V3106. Possibly index is out of bound.
The analyzer has detected a case where indexing into a variable of array
, list
, or string
type may throw an IndexOutOfRangeException
exception if the index value is outbound the valid range.
For example, it may happen when iterating through an array in a loop:
int[] buff = new int[25];
for (int i = 0; i <= 25; i++)
buff[i] = 10;
Note. The first item's index is 0
and the last one is the array size minus one.
The fixed code:
int[] buff = new int[25];
for (int i = 0; i < 25; i++)
buff[i] = 10;
Such errors may occur not only in loops, but also in conditions with incorrect index checks:
void ProcessOperandTypes(ushort opCodeValue, byte operandType)
{
var OneByteOperandTypes = new byte[0xff];
if (opCodeValue < 0x100)
{
OneByteOperandTypes[opCodeValue] = operandType;
}
...
}
The fixed version:
void ProcessOperandTypes(ushort opCodeValue, byte operandType)
{
var OneByteOperandTypes = new byte[0xff];
if (opCodeValue < 0xff)
{
OneByteOperandTypes[opCodeValue] = operandType;
}
...
}
These errors also can occur when directly accessing a specific element of an array or a list.
void Initialize(List<string> config)
{
...
if (config.Count == 16)
{
var result = new Dictionary<string, string>();
result.Add("Base State", config[0]);
...
result.Add("Sorted Descending Header Style", config[16]);
}
...
}
In this example, the error occurs in the number of entries in the config
list.
The fixed version:
void Initialize(List<string> config)
{
...
if (config.Count == 17)
{
var result = new Dictionary<string, string>();
result.Add("Base State", config[0]);
...
result.Add("Sorted Descending Header Style", config[16]);
}
...
}
Indexing with a value obtained from an external source is unsafe:
void ProcessBuff()
{
int[] buff = new int[64];
....
var indexStr = Request.QueryString["index"];
if (Int32.TryParse(indexStr, out int index))
{
int indexValue = buff[index];
....
}
}
The value for indexStr
, obtained from an external source, is converted to int
and assigned to the index
variable. This value is then used to access an element of the buff
array. If index
is less than 0
or greater than 63
, it may result in an overflow.
To fix this code, check the index before a call:
void ProcessBuff()
{
int[] buff = new int[64];
....
var indexStr = Request.QueryString["index"];
if ( Int32.TryParse(indexStr, out int index)
&& index >= 0 && index < buff.Length) // <=
{
int indexValue = buff[index];
....
}
}
This diagnostic is classified as:
You can look at examples of errors detected by the V3106 diagnostic. |