The array index out of bounds error is a special case of the buffer overflow error. It occurs when the index used to address array items exceeds the allowed value. It's the area outside the array bounds which is being addressed, that's why this situation is considered a case of undefined behavior. Absence of array overrun control in C and C++ is the factor that makes this error possible.
The array index out of bounds error can be diagnosed with static or dynamic code analyzers. Diagnostics for these defects are quite urgent, as it may take much time before these errors reveal themselves. Whether a program containing them will work or not depends on the compiler version or operating system version.
Here are some examples of this error found in the code of real open-source projects by the PVS-Studio static analyzer.
The Dumb project, Dynamic Universal Music Bibliotheque.
struct IT_SAMPLE
{
....
unsigned char filename[14];
....
};
static int it_riff_dsmf_process_sample(
IT_SAMPLE * sample, const unsigned char * data, int len)
{
int flags;
memcpy( sample->filename, data, 13 );
sample->filename[ 14 ] = 0;
....
}
The 'filename' array consists of 14 items, but the 'it_riff_dsmf_process_sample' function addresses the 14-th item lying outside the array bounds. Programmers often make this mistake because they forget that array indexing in C/C++ starts with zero and ends with a value that is one less than the array size.
Let's have a look at one more similar error. The Wolfenstein 3D project, a computer game by 'id Software'.
typedef struct bot_state_s
{
...
char teamleader[32]; //netname of the team leader
...
} bot_state_t;
void BotMatch_StartTeamLeaderShip(
bot_state_t *bs, bot_match_t *match)
{
...
bs->teamleader[sizeof( bs->teamleader )] = '\0';
...
}
The error in this case is this: 'sizeof(Array)' returns the array size, while you need to subtract one from the result returned by 'sizeof(Array)' to address the last item.
Here you may see other samples of this error found through the static analysis method.
0