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.
Code | Description | Enabled | Reported | Platform |
---|---|---|---|---|
READ_BAD_INDEX | Reading array out of range | Runtime | Windows/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
- Line 2: Source line at which the problem was detected.
- Line 3: Description of the problem and the expression that is in error.
- Line 4: Illegal index value used.
- Line 5: Valid index range for this array.
- Line 6: 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); }