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]
	Index used: 10
	Valid range: 0 thru 9 (inclusive)
	Stack trace where the error occurred:
		main() readindx.c, 11

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);
}