主要内容

MISRA C:2012 Rule 1.3

R2026b

There shall be no occurrence of undefined or critical unspecified behaviour

描述

There shall be no occurrence of undefined or critical unspecified behaviour 1 .

理由

导致未定义行为或关键未指定行为的 C 代码可能会产生意外或不正确的结果。此类代码在不同的实现中可能具有不同的行为。由代码中未定义的行为引发的问题可能难以分析,因为编译器在进行代码优化时,可能会假定未定义的行为不会发生。

注意

许多 MISRA C:2012 规则涉及特定未定义行为或关键未指定行为。本规则适用于任何其他规则未涉及的未定义行为或关键未指定行为。

Polyspace 实现

Polyspace® 会标记以下未定义行为或关键未定义行为的实例:

  • 在位字段上使用 offsetof。

  • 当第二个参量不是第一个参量的 struct 字段时,使用 offsetof。

  • 在未指定标识符的情况下使用 defined。

  • 使用的宏在展开时包含 defined 运算符。

  • 使用不完整类型的数组。

  • 以错误数量的参量调用类似宏的函数(仅限 C90)。

故障排除

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

示例

全部展开

#include <stddef.h>     
static int bar = 0;
extern int bar;         /* Violation (8.8)*/

struct str {
  char a:8;
  char b[10];
  char c;
};
void foo() {
  
  offsetof(struct str, a);//Noncompliant
  offsetof(struct str, d);//Noncompliant
}

在此示例中,函数 foo 对位字段 str.a 使用了宏 offsetof。此行为属于未定义行为,Polyspace 会将其标记出来。随后,该函数对 str.d 调用了 offsetof。由于 d 不是 str 的字段,因此 Polyspace 会将其标记出来。这些问题可能会导致编译错误。

变量 bar 被同时声明为内部链接和外部链接。根据 C99 标准,在同一文件中将变量声明为同时具有内部存储和外部存储属于未定义行为。Polyspace 会将这种未定义行为标记为违反规则 8.8。请参阅 MISRA C:2012 Rule 8.8。

检查信息

组:标准 C 环境
类别:必需
AGC 类别:必需
PQL 名称:std.misra_c_2012.R1_3

版本历史记录

在 R2014b 中推出

全部展开


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:2025

  • MISRA C++:2008

  • MISRA C++:2023

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