Array subscripts out of bounds
The GNU Compiler Collection (GCC) and the Systems/C and Systems/C++ compilers generate similar warnings when there is a problem with array boundaries in your code.
GNU Compiler Collection (GCC) compiler array warning
Problem: I received the following warning: array subscript is above array bounds [-Warray-bounds]
Solution: The GNU Compiler Collection (GCC) 4.6.3 issues a warning when it detects the access of an array element that is above the array bounds. The warning usually occurs when code loops through an array and incorrectly checks for the end of the array. The array bounds [-Warray-bounds] warning is enabled by specifying the -Wall compiler option.
For
example, fix this code:
char myarray[10]; /* has elements [0] through [9] */
for (i = 0, i <= 10; i++)
myarray[i] = ‘\0’;
Corrected code:
char myarray[10]; /* has elements [0] through [9] */
for (i = 0, i <= 9; i++)
myarray[i] = ‘\0’;
This corrected code would also work:
char myarray[10]; /* has elements [0] through [9] */
for (i = 0, i < 10; i++)
myarray[i] = ‘\0’;
Note: The -Warray-bounds warning can be valuable in detecting legitimate code problems; therefore,
consider keeping the warning enabled to improve code quality.
Systems/C and Systems/C++ compiler array warning
Problem: I received the following warning: Warning #2367: array subscript out of range
Solution: The Dignus Systems/C and Systems/C++ compilers
issue a warning when the code tries to access an array element that
is beyond the maximum defined index in the array. For example, in
the following code, a warning is generated in code that tries to access
byte 5 in the uat_ss_name field , but the uat_ss_name field is defined
as 4 bytes (array elements 0 - 3) in size:
struct uatbc_area
{
void *uat_ssu_ptr; /* return area of SSU entry ptr */
char uat_ss_name[4]; /* return area of parent SSU name */
⋮
}
⋮
uatbc_parm.uat_ss_name[5] = '\';
The fix for the previous example is to ensure that
an array element that is beyond the last defined element is not accessed.
In this example, the data is copied to a new structure so that a NULL
character can be appended to the end:
char copyof_uat_ss_name[5];
strncpy(copyof_uat_ss_name, uatbc_parm.uat_ss_name, 4);
copyof_uat_ss_name[4] = '\0';