主要内容

MISRA C:2023 Rule 12.5

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

自 R2024a 起

描述

规则定义

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

此规则来自 MISRA C™:2012 Amendment 1。

理由

作用在数组上的 sizeof 运算符通常返回数组大小(以字节为单位)。例如,在下面的代码中,sizeof(arr) 返回 arr 的大小(以字节为单位)。

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

然而,当数组作为函数参数时,它会退化为一个指针。作用于数组的 sizeof 运算符返回相应的指针大小,而非数组大小。

对作为函数参数的数组使用 sizeof 运算符通常是无意中的编程错误。

故障排除

如果您预期会出现违规,但未看到该违规,请参阅诊断为何编码规范违规未按预期显示

示例

全部展开

#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 */
}

在此示例中,不管数组中看起来有多少个成员(在本例中为 4 个),变量 numElements 的值始终为 1,因为 A 的类型是 int32_t * 而不是 int32_t[4]

变量 numElements_glbA 具有预期的值 5,因为 sizeof 运算符作用于全局数组 glbA

检查信息

组:表达式
类别:强制
AGC 类别:强制

版本历史记录

在 R2024a 中推出


1 All MISRA coding rules and directives are © Copyright The MISRA Consortium Limited 2021.

The MISRA coding standards referenced in the Polyspace® Bug Finder™ documentation are from the following MISRA standards:

  • MISRA C:2004

  • MISRA C:2012

  • MISRA C:2023

  • MISRA C++:2008

  • MISRA C++:2023

MISRA and MISRA C are registered trademarks of The MISRA Consortium Limited 2021.