主要内容

本页采用了机器翻译。点击此处可查看最新英文版本。

MISRA C:2012 Rule 1.3

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 类别:必需

版本历史记录

在 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++:2008

  • MISRA C++:2023

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