MISRA.EXPR.SIZEOF.ARRAY_PARAM.2012_AMD1The sizeof operator shall not have an operand which is a function parameter declared as "array of type" MISRA C 2012 Rule 12.5: The sizeof operator shall not have an operand which is a function parameter declared as "array of type"Category: Mandatory Analysis: Decidable, Single Translation Unit Applies to: C90, C99 AmplificationThe function parameter A in void f ( int32_t A[ 4 ] ) is declared as “array of type”. RationaleThe sizeof operator can be used to determine the number of elements in an array A: size_t arraySize = sizeof ( A ) / sizeof ( A[ 0 ] ); This works as expected when A is an identifier that designates an array, as it has type “array of type”. It does not “degenerate” to a pointer and sizeof ( A ) returns the size of the array. However, this is not the case when A is a function parameter. The Standard states that a function parameter never has type “array of type” and a function parameter declared as an array will “degenerate” to “pointer to type”. This means that sizeof ( A ) is equivalent to sizeof ( int32_t * ), which does not return the size of an array. Exampleint32_t glbA[] = { 1, 2, 3, 4, 5 }; void f ( int32_t A[ 4 ] ) { /* * The following is non-compliant as it always gives the same answer, * irrespective of the number of members that appear to be in the array * (4 in this case), because A has type int32_t * and not int32_t[ 4 ]. * As sizeof ( int32_t * ) is often the same as sizeof ( int32_t ), * numElements is likely to always have the value 1. */ uint32_t numElements = sizeof ( A ) / sizeof ( int32_t ); /* * The following is compliant as numElements_glbA will be given the * expected value of 5. */ uint32_t numElements_glbA = sizeof ( glbA ) / sizeof ( glbA[ 0 ] ); } |