V582. Consider reviewing the source code which operates the container.


The analyzer detected a potential error related to handling a fixed-sized container. One of our users advised us to implement this diagnostic. This is how he has formulated the task.

In order to handle arrays of a fixed size, we use the following template class:

template<class T_, int numElements > class idArray
{
public:
  int Num() const { return numElements; };
  .....
  inline const T_ & operator[]( int index ) const {
    idassert( index >= 0 ); 
    idassert( index < numElements );
    return ptr[index];
  };
  inline T_ & operator[]( int index ) {
    idassert( index >= 0 ); 
    idassert( index < numElements );
    return ptr[index];
  };
private:
  T_ ptr[numElements];
};

It has no performance overhead in release builds, but does index range checking in debug builds. Here is an example of incorrect code:

idArray<int, 1024> newArray; 
newArray[-1] = 0; 
newArray[1024] = 0;

The errors will be detected on launching the debug version. But we would like to be able to detect such errors using static analysis at the compilation time.

It is this type of issues that the V582 diagnostic is intended to detect. If a class is used in a program that makes use of a fixed-sized container's functionality, the analyzer tries to make sure that the index does not go beyond its boundaries. Here are examples of this diagnostic:

idArray<float, 16> ArrA;
idArray<float, 8> ArrB;
for (size_t i = 0; i != 16; i++)
  ArrA[i] = 1.0f;
for (size_t i = 0; i != 16; i++)
  ArrB[i] = 1.0f;

The analyzer will generate the following message on this code:

V582 Consider reviewing the source code which operates the 'ArrB' container. The value of the index belongs to the range: [0..15].

The error here is that the both loops handle 16 items, although the second array contains only 8 items. This is the correct code:

for (size_t i = 0; i != 16; i++)
  ArrA[i] = 1.0f;
for (size_t i = 0; i != 8; i++)
  ArrB[i] = 1.0f;

Note that passing of too large or too small indexes does not necessarily indicate an error in the program. For instance, the [] operator can be implemented in the following way:

inline T_ & operator[]( int index ) {
  if (index < 0) index = 0;
  if (index >= numElements) index = numElements - 1;
  return ptr[index];
};

If you use such classes and get too many false reports, you should turn off the V582 diagnostic.

Note. The analyzer does not possess an AI and its capabilities of searching for defects when handling containers are limited. We are working on improving the algorithms, so if you have noticed obviously false reports or, on the contrary, cases when the analyzer does not generate the warning, please write to us and send us the corresponding code sample.

According to Common Weakness Enumeration, potential errors found by using this diagnostic are classified as CWE-119, CWE-125, CWE-787.


Bugs Found

Checked Projects
334
Collected Errors
12 668