In this section:

Overview

This error is generated whenever an illegal value will be used to index an array. It is a particularly common error that can be very difficult to detect, especially if the out-of-range elements happen to have zero values. If this error can be detected during compilation, an error will be issued instead of the normal runtime error.


CodeDescriptionEnabledReportedPlatform
READ_BAD_INDEX

Reading array out of range

(tick)RuntimeWindows/Unix


Problem

The following code attempts to access an illegal array element due to an incorrect loop range.

/*
 * File: readindx.c
 */
int a[10];
int junk;
main()
{
	int i, tot=0;

	for(i=1; i<=10; i++)
	tot += a[i];
	return (0);
}

Diagnosis at Runtime

[readindx.c:11] **READ_BAD_INDEX**
>>			 tot += a[i];
	Reading array out of range: a[i]

---- Associated Common Weakness Enumerations ----
CWE-119: Improper Restriction of Operations within the Bounds of a Memory Buffer
CWE-125: Out-of-bounds read
CWE-126: Buffer over-read
CWE-786: Access of memory location before start of buffer
CWE-786: Access of memory location after end of buffer

  Index used: 10
	Valid range: 0 thru 9 (inclusive)
	Stack trace where the error occurred:
		main() readindx.c, 11
  • Line 2: Source line at which the problem was detected.
  • Line 3: Description of the problem and the expression that is in error.
  • Line 5-10: CWEs associated with the problem.
  • Line 12: Illegal index value used.
  • Line 13: Valid index range for this array.
  • Line 14: Stack trace showing the function call sequence leading to the error.

Repair

Typical sources of this error include loops with incorrect initial or terminal conditions, as in this example, for which the corrected code is:

main()
{
	int i, tot=0, a[10];

	for(i=0; i<sizeof(a)/sizeof(a[0]); i++)
		tot += a[i];
	return (0);
}

References

The table below shows Common Weakness Enumerations associated with this error.

CWEDescription
CWE-119Improper Restriction of Operations within the Bounds of a Memory Buffer
CWE-125Out-of-bounds read
CWE-126Buffer over-read
CWE-786Access of memory location before start of buffer
CWE-786Access of memory location after end of buffer
  • No labels