This diagnostic rule is based on the MISRA (Motor Industry Software Reliability Association) software development guidelines.
This diagnostic rule is relevant only for C.
The sizeof
operator returns the size of a pointer instead of the size of an array when the array is passed to the function by copy.
Look at the following code snippet:
char A[100];
void Foo(char B[100])
{
}
In this code fragment, the A
object is an array, and the sizeof(A)
expression returns the value of 100
.
The B
object is a regular pointer, despite its declaration. The 100
value in brackets is just a hint to a programmer that the passed array must contain one hundred elements. Thus, the sizeof(B)
expression will be equal to the size of the pointer, which is implementation-defined. For example, for 32-bit systems, its size is 4 bytes and for 64-bit systems—8 bytes.
The warning is issued when the size of a pointer—passed as an argument in the array_type name[N]
format—is evaluated. Most likely, such code contains an error. Look at the example:
void Foo(float array[3])
{
const size_t n = sizeof(array) / sizeof(array[0]);
for (size_t i = 0; i < n; ++i)
array[i] = 0.0f;
}
The sizeof(array) / sizeof(array[0])
expression evaluates the array size incorrectly. As a result, it will not be completely filled with the 1.0f
value.
To prevent such errors, pass the number of array elements explicitly.
The fixed code:
void Foo(float *array, size_t count)
{
for (size_t i = 0; i < count; ++i)
array[i] = 1.0f;
}