主要内容

MISRA C++:2023 Rule 11.3.1

Variables of array type should not be declared

自 R2024b 起

描述

Variables of array type should not be declared. 1

理由

C 样式数组对象的大小信息并非始终都会保留。使用像 std::array 这样容器来保留大小信息会更安全。

作为例外,如果立即用字符串字面值初始化数组,则声明 const char 数组并不违规。

Polyspace 实现

如果您的代码包含 C 样式的数组,则 Polyspace® 会报告违反此规则。当向函数传递传统的 C 样式数组时,Polyspace 不会报告违反此规则,因为数组在作为参量传递给函数时会衰减为指针。

故障排除

如果您预期会出现违规,而 Polyspace 未报告该违规,请参阅诊断为何编码规范违规未按预期显示

示例

全部展开

在此示例中,函数 foo() 中声明了一个 C 样式的整数数组 numbers。此数组的大小无法立即确定。函数 sum() 通过使用第二个参数 size 来检查传入数组 numbers 的边界。由于 numbers 的大小信息未被保留,因此 sum() 无法验证 size 是否表示 numbers 的长度。Polyspace 报告违反了此规则。

#include <cstdlib>

 int sum(const int *numbers, std::size_t size);

void foo() {
	int numbers[] = { 1, 2, 3, 4, 5 };//Noncompliant
	std::size_t size = sizeof(numbers) / sizeof(numbers[0]);

	int totalSum = sum(numbers, size);
	//...
}

检查信息

组:声明符
类别:建议
PQL 名称:std.misra_cpp_2023.R11_3_1

版本历史记录

在 R2024b 中推出


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.