主要内容

本页翻译不是最新的。点击此处可查看最新英文版本。

MISRA C:2023 Rule 9.1

The value of an object with automatic storage duration shall not be read before it has been set

自 R2024a 起

描述

报告中的消息:

规则定义

The value of an object with automatic storage duration shall not be read before it has been set 1 .

理由

对于具有自动存储期的变量,将在封闭代码块的开头为其分配内存,在末尾为其解除分配内存。所有非全局变量都具有此存储期,但那些声明为 staticextern 的变量除外。

具有自动存储期的变量不会自动初始化,且具有不确定的值。因此,您不能在通过写入操作设置变量的值之前,读取此变量。

Polyspace 实现

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

Polyspace 会报告未初始化的 _Atomic 限定变量违反了此问题规则。您可以使用代码注释来对这些违规进行申述。请参阅为代码添加注解并隐藏已知或可接受的结果。或者,您可以使用 Polyspace 用户界面来对这些违规进行申述。请参阅通过 Bug 修复或申述在 Polyspace 用户界面中处理结果

故障排除

如果您预计存在违规,但未看到该违规,请参阅Diagnose Why Coding Standard Violations Do Not Appear as Expected

示例

全部展开

如果 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              
   
}

如果 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;
}

检查信息

组:初始化
类别:强制
AGC 类别:强制

版本历史记录

在 R2024a 中推出


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.