>
>
>
V697. Number of elements in the allocat…


V697. Number of elements in the allocated array equals the size of a pointer in bytes.

The number of items in an array allocated by the 'new' operator equals the pointer size in bytes, which makes this code fragment very suspicious.

Take a look at an example demonstrating how such a fragment is introduced into the code. At first, the program contained a fixed array consisting of bytes. We needed to create an array of the same size but consisting of float items. As a result, we wrote the following code:

void Foo()
{
  char A[10];
  ....
  float *B = new float[sizeof(A)];
  ....
}

We won't discuss the quality of this code now; what we are interested in is that the 'A' array has become dynamic too as a result of refactoring. The fragment where the 'B' array is created was forgotten to be changed. Because of that, we get the following incorrect code:

void Foo(size_t n)
{
  char *A = new char[n];
  ....
  float *B = new float[sizeof(A)];
  ....
}

The number of items in the 'B' array is 4 or 8, depending on the platform bitness. It is this problem that the analyzer detects.

The fixed code:

void Foo(size_t n)
{
  char *A = new char[n];
  ....
  float *B = new float[n];
  ....
}

This diagnostic is classified as: