V511. The sizeof() operator returns pointer size instead of array size.


The 'sizeof' operator returns size of a pointer, not of an array, when the array was passed by value to a function.

There is one specific feature of the language you might easily forget about and make a mistake. Look at the following code fragment:

char A[100];
void Foo(char B[100])
{
}

In this code, the A object is an array and the sizeof(A) expression will return value 100.

The B object is simply a pointer. Value 100 in the square brackets indicates to the programmer that he is working with an array of 100 items. But it is not an array of a hundred items which is passed into the function - it is only the pointer. So, the sizeof(B) expression will return value 4 or 8 (the size of the pointer in a 32-bit/64-bit system).

The V511 warning is generated when the size of a pointer is calculated which is passed as an argument in the format "TypeName ArrayName[N]". Such code is most likely to have an error. Look at the sample:

void Foo(float array[3])
{
  size_t n = sizeof(array) / sizeof(array[0]);
  for (size_t i = 0; i != n; i++)
    array[i] = 1.0f;
}

The function will not fill the whole array with value 1.0f but only 1 or 2 items depending on the system's capacity.

Win32: sizeof(array) / sizeof(array[0]) = 4/4 = 1.

Win64: sizeof(array) / sizeof(array[0]) = 8/4 = 2.

To avoid such errors, we must explicitly pass the array's size. Here is correct code:

void Foo(float *array, size_t arraySize)
{
  for (size_t i = 0; i != arraySize; i++)
    array[i] = 1.0f;
}

Another way is to use a reference to the array:

void Foo(float (&array)[3])
{
  size_t n = sizeof(array) / sizeof(array[0]);
  for (size_t i = 0; i != n; i++)
    array[i] = 1.0f;
}

This diagnostic is classified as:

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