如何解析 C 代码的 MISRA C:2012 规则 13.2 和 13.3?
我有 C 源代码,我正在使其符合 MISRA 标准。我收到与 MISRA 2012 规则 13.3 和 13.2 相关的以下错误:
-
递增/递减操作与其他具有副作用的操作相结合 [MISRA 2012 规则 13.3,咨询]buf[count++] = U1RXREG;
-
双方都有副作用 [MISRA 2012 规则 1.3,必需],[MISRA 2012 规则 13.2,必需] buf[count] = U1RXREG;
问题 1 的源代码:
void UART_call(void)
{
if(count < BUF_SIZE)
{
buf[count++] = U1RXREG;
Flag = 1;
}
else
{
count = 0;
Flag = 0;
}
}
解决问题 1 代码中的 13.3 错误后,我收到 MISRA 1.3 和 13.2 错误。问题2的源码:
void UART_call(void)
{
if(count < BUF_SIZE)
{
buf[count] = U1RXREG;
count = count + 1U;
Flag = 1;
}
else
{
count = 0;
Flag = 0;
}
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
正如您似乎已经注意到的那样,通过将增量移出赋值表达式来解决:
其背后的基本原理是防止编写诸如 buf[count++] = count; 之类的错误
我想说这是误报。
buf[count] = U1RXREG;
行是无害的。发出警告的原因是,
U1RXREG
显然是 UART 硬件的易失性限定接收寄存器,并且 MISRA-C 不喜欢将易失性访问与同一表达式中的其他内容混合,尤其是与另一个“副作用”,在本例中为 count 的++
以及对buf
的赋值。这是静态分析器误报的常见来源,尽管有时它们确实会发现与此相关的真正错误,例如您询问的 && 案例.com/questions/54084453/how-to-make-c-code-to-misra-c2012-compliance">昨天。假设是 32 位寄存器,那么修复它的迂腐方法是使用临时变量:
就机器代码和程序行为而言,这相当于原始代码。
This is as you seem to have noted, solved by moving the incrementation out of the assignment expression:
The rationale behind this is to prevent writing bugs such as
buf[count++] = count;
I'd say this is a false positive. The line
buf[count] = U1RXREG;
is harmless.The reason for the warning is that
U1RXREG
is obviously a volatile-qualified rx register of the UART hardware, and MISRA-C doesn't like mixing volatile access with other things in the same expression, particularly not with another "side-effect", in this case the++
of count together with the assignment tobuf
. It's a common source for false positives from static analysers, though sometimes they do find real bugs related to this, as in the&&
case you asked about yesterday.Assuming 32 bit registers, then the pedantic way to fix it is to use a temporary variable:
As far as machine code and program behavior are concerned, this is equivalent to the original code.