In this section:
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.
|
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);
} |
[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 |
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);
} |
The table below shows Common Weakness Enumerations associated with this error.
| CWE | Description |
|---|---|
| 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 |