主要内容

AUTOSAR C++14 Rule A8-5-0

All memory shall be initialized before it is read

描述

All memory shall be initialized before it is read.

理由

C++ 标准没有指定未初始化的内存可以是哪些值。此值不可预测,并且在程序每次运行时可能不同。读取和使用未初始化内存的值会导致意外行为。

Polyspace 实现

如果您的代码包含以下问题,则 Polyspace® 会报告违反此规则:

  • 未初始化的变量:在初始化前读取变量。

  • 未初始化的成员:未初始化类构造函数中的类成员:

  • 未初始化的指针:在初始化前解引用指针。

故障排除

如果您预期会出现违规,而 Polyspace 未报告该违规,请参阅诊断为何编码规范违规未按预期显示

示例

全部展开

如果 command 不为 2,则变量 val 未赋值。在这种情况下,函数 get_sensor_value 的返回值无法确定。

int get_sensor_value(void)
{
    extern int getsensor(void);
    int command;
    int val;

    command = getsensor();
    if (command == 2) 
      {
        val = getsensor();
      }

    return val; //Noncompliant              
   
}

在此示例中,如果 flag 不为 0,则成员 _c 未初始化。

该缺陷出现在构造函数的右花括号上。下面是有关在源代码中导航的一些提示:

  • 结果详细信息窗格中,查看哪些成员未初始化。

  • 要导航到类定义,请右键点击在构造函数中被初始化的某个成员。右键点击该函数并选择转至定义。在类定义中,您可以看到所有成员,包括那些在构造函数中未被初始化的成员。

class MyClass {
public:
    explicit MyClass(int);
private:
    int _i;
    char _c;
};

MyClass::MyClass(int flag) {
    if(flag == 0) {
        _i = 0;
        _c = 'a';
    }
    else {
        _i = 1;
    }
}//Noncompliant

如果 prev 不是 NULL,则指针 pi 未分配地址。但是,pi 在每个执行路径上都被解引用,无论 prev 是否为 NULL

#include <stdlib.h>

int* assign_pointer(int* prev)
{
    int j = 42;
    int* pi;

    if (prev == NULL) 
      {
        pi = (int*)malloc(sizeof(int));
        if (pi == NULL) return NULL;
      }

    *pi = j; //Noncompliant                    

    return pi;
}

检查信息

组:声明符
类别:必需、自动
PQL 名称:std.autosar_cpp14.A8_5_0

版本历史记录

在 R2019a 中推出

全部展开