Our website uses cookies to enhance your browsing experience.
Accept
to the top
>
>
>
V557. Possible array overrun.
menu mobile close menu
Analyzing projects
Additional information
toggle menu Contents

V557. Possible array overrun.

Jun 13 2012

The analyzer has detected a potential memory access outside an array. The most common case is an error occurring when writing the \0 character after the last array's element.

The error example:

struct IT_SAMPLE
{
  unsigned char filename[14];
  ...
};

static int it_riff_dsmf_process_sample(
  IT_SAMPLE * sample, const unsigned char * data)
{
  memcpy( sample->filename, data, 13 );
  sample->filename[ 14 ] = 0;
  ...
}

The last array's element has index 13, not 14. So, the correct code looks like this:

sample->filename[13] = 0;

It is recommended to use an expression involving the sizeof() operator instead of an explicit index' value in such cases. However, it is possible to make a mistake even in this case.

The example:

typedef wchar_t letter;
letter    name[30];
...
name[sizeof(name) - 1] = L'\0';

The sizeof(name) - 1 looks correct. However, developers may have forgotten that they handled the wchar_t type and not char. As a result, the \0 character is written far outside the array's boundaries.

The fixed code:

name[sizeof(name) / sizeof(*name) - 1] = L'\0';

To simplify writing of such constructs, you may use this special macro:

#define str_len(arg) ((sizeof(arg) / sizeof(arg[0])) - 1)
name[str_len(name)] = L'\0';

The analyzer detects some errors when the index is represented by a variable whose value might run out of the array's boundaries. For example:

int buff[25];
for (int i=0; i <= 25; i++)
  buff[i] = 10;

The correct code:

int buff[25];
for (int i=0; i < 25; i++)
  buff[i] = 10;

Note that the analyzer might make mistakes when handling such value ranges and issue false alarms.

Checking the upper bound of an array

The analyzer can also detect a potential array out-of-bounds access when the code checks only the lower index bound but not the upper one.

The example:

int arr[6];

void foo(int i)
{
  if (i >= 0) 
  {
    arr[i] = 0; // <= V557
  }
}

The i >= 0 condition only guarantees that the array index is non-negative; it doesn't prevent a buffer overflow. If the i variable has a value greater than 5, the code accesses the arr array out of bounds.

The fixed code:

int arr[6];

void foo(int i)
{
  if (i >= 0 && i < 6) 
  {
    arr[i] = 0; //ok
  }
}

By default, checking the upper bound of an array is disabled. To enable it, add the following comment to the configuration file (.pvsconfig) or source file:

//+V557 CHECK_UPPER_BOUND:ON

To disable it, use the following comment:

//+V557 CHECK_UPPER_BOUND:OFF

This diagnostic rule is classified as:

You can look at examples of errors detected by the V557 diagnostic.