MISRA C:2012 Rule 18.4
The +, -, += and -= operators should not be applied to an expression of pointer type
描述
规则定义
The +, -, += and -= operators should not be applied to an expression of pointer type 1 .
理由
指针运算的首选形式是使用数组下标语法 ptr[expr]
。这种语法清晰明了,比指针操作更少出错。通过指针操作,任何显式计算的指针值都有可能访问意外或无效的内存地址。数组索引也会访问意外或无效的内存,但更易于审查。
对于一位新的 C 程序员来说,表达式 ptr+1
可能会被误解为“1 加上 ptr
的地址”。然而,新的内存地址取决于指针目标的大小(以字节为单位)。这种混淆可能导致意外行为。
在谨慎使用的情况下,通过 ++
进行指针操作可以更加自然(例如,在内存测试过程中依次访问内存位置)。
Polyspace 实现
根据 MISRA C™:2012 规范,规则检查项会标记指针运算,例如 Pointer + Integer
、Integer + Pointer
、Pointer - Integer
等。
故障排除
如果您预期会出现违规,但未看到该违规,请参阅诊断为何编码规范违规未按预期显示。
示例
检查信息
组:指针和数组 |
类别:建议 |
AGC 类别:建议 |
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.