Main Content

MISRA C:2012 Rule 12.5

The sizeof operator shall not have an operand which is a function parameter declared as “array of type”

Description

Rule Definition

The sizeof operator shall not have an operand which is a function parameter declared as “array of type”.

This rule comes from MISRA C™: 2012 Amendment 1.

Rationale

The sizeof operator acting on an array normally returns the array size in bytes. For instance, in the following code, sizeof(arr) returns the size of arr in bytes.

int32_t arr[4];
size_t numberOfElements = sizeof (arr) / sizeof(arr[0]);

However, when the array is a function parameter, it degenerates to a pointer. The sizeof operator acting on the array returns the corresponding pointer size and not the array size.

The use of sizeof operator on an array that is a function parameter typically indicates an unintended programming error.

Additional Message in Report

The sizeof operator shall not have an operand which is a function parameter declared as “array of type”.

Troubleshooting

If you expect a rule violation but do not see it, refer to Diagnose Why Coding Standard Violations Do Not Appear as Expected.

Examples

expand all

#include <stdint.h> 
int32_t glbA[] = { 1, 2, 3, 4, 5 };
void f (int32_t A[4])
{
 	uint32_t numElements = sizeof(A) / sizeof(int32_t);  /* Non-compliant */
	uint32_t numElements_glbA = sizeof(glbA) / sizeof(glbA[0]);  /* Compliant */
}

In this example, the variable numElements always has the same value of 1, 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].

The variable numElements_glbA has the expected vale of 5 because the sizeof operator acts on the global array glbA.

Check Information

Group: Expressions
Category: Mandatory
AGC Category: Mandatory

Version History

Introduced in R2017a