In this section:

Overview

This error is generated whenever an illegal value will be used to index an array that is being written. If this error can be detected during compilation, a compilation error will be issued instead of the normal runtime error.

CodeDescriptionEnabledReportedPlatform
WRITE_BAD_INDEXWriting array out of range(tick)RuntimeWindows/Unix


Problem

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

/*
 * File: writindx.c
 */
main()
{
	int i, a[10];

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

Other problems include writimd2.c and writimd3.c. A diagnosis similar to the one that follows applies to both.

Diagnosis at Runtime

[writindx.c:9] **WRITE_BAD_INDEX**
>>		a[i] = 0;
Writing array out of range: a[i]

---- Associated Common Weakness Enumerations ----
CWE-119: Improper Restriction of Operations within the Bounds of a Memory Buffer
CWE-124: Buffer Underwrite
CWE-787: Out-of-bounds write
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() writindx.c, 9
**Memory corrupted. Program may crash!!**
  • 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.
  • Line 16: Informational message indicating that a serious error has occurred which may cause the program to crash. 

Repair

This is normally a fatal error and is often introduced algorithmically. Other common sources include loops with incorrect initial or terminal conditions, as in this example, for which the corrected code is the following:

main()
{
	int i, a[10];
	for(i=; i<sizeof(a)/sizeof(a[0]); i++)
	a[i] = 0;
	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-124Buffer Underwrite
CWE-787Out-of-bounds write
CWE-786Access of memory location before start of buffer
CWE-786Access of memory location after end of buffer
  • No labels