Misra 5-0-15-指针算术 - 违反规则
以下代码违反了Misra C ++规则5-0-15:数组索引是指针算术的唯一形式。
(1)
void doSomething(const uint8_t *&ptr, size_t num) {
ptr += num;
}
增加任何指针也违反了上述规则:
(2)
const uint8_t *ptr = ... ;
*ptr++;
我发现一个非常相似的问题在这里,但是在那里发问者使用数组。我使用指示器。
是否有替代符号或其他方法将数字添加到(1)/增量(2)指针以解决此违规行为?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
因此使用数组索引。
可以通过异常来使用 增量和减少操作员。用增量进行解雇无效。必须有两个表达式。
So use array indexing.
Increment and decrement operators can be used by exception. Doing dereference with incrementing is invalid. There have to be two expressions.
“数组索引应是指针算术的唯一形式”规则是从Misra C:2004继承的,并且关于该规则是否有意义的讨论很早就进行了讨论。该规则背后的理由是防止
*(arr+i)
arr [i]
样式,我认为没有人质疑后者更可读性因此优先。但是,Misra C:2004文件中的示例令人困惑 - 它不允许在称为指示器的变量上索引数组样式。但是显然,在函数的情况下,我们是否将某些内容声明为
void func(int* ptr)
或void func(int ptr [])
,因为这些是100%同等,这要归功于C的参数调整规则。实际上,[]
操作员只能与指针操作数一起使用,如下所示: do pointers支持“阵列样式索引”?因此,此规则导致了很多误报。这是Misra C:2012中固定的众多因素之一,规则18.4专注于指针自身,而不是宣布某物的方式。 Misra C:2004和Misra C ++:2008仍然会有旧的措辞和示例,因此,如果您使用这些措辞,则应用一粒盐来服用规则。
在您的特定情况下,使用
const uint8_t *& ptr
vsconst uint8_t& ptr []
没关系。ptr += num;
是可疑的部分。与该规则无关的是,将一系列参考文献的指针也很可变,如果可以使用较不复杂的替代方案,则需要进行审查。
The "array indexing shall be the only form of pointer arithmetic" rule was inherited from MISRA C:2004 and there were discussions early on about whether the rule made sense or not. The rationale behind the rule was to prevent
*(arr+i)
style overarr[i]
style and I don't think anyone is questioning that the latter is more readable and therefore preferred.However, the examples in the MISRA C:2004 document were confusing - it wouldn't allow array style indexing on variables declared as pointers. But obviously in case of functions, it doesn't matter if we declare something as
void func (int* ptr)
orvoid func (int ptr[])
because these are 100% equivalent thanks to the parameter adjustment rules of C. In fact the[]
operator can only be used with pointer operands as explained here: Do pointers support "array style indexing"? So this rule lead to a lot of false positives.This is one of many things that were fixed in MISRA C:2012, where rule 18.4 is focusing on the pointer artithmetic itself rather than how something was declared. MISRA C:2004 and MISRA C++:2008 will still have the old wording and examples though, so if you are using those, you should take the rule with a grain of salt.
In your specific case, using
const uint8_t *&ptr
vsconst uint8_t& ptr[]
doesn't matter.ptr += num;
is the questionable part.Unrelated to the rule, having a pointer to an array of references is pretty fishy as well and would need to be reviewed, in case it is possible to use less complex alternatives.