Main Content

MISRA C:2012 Rule 9.1

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

Description

Message in Report:

Note

Using Code Prover for checking coding rules is no longer supported. See Version History.

Rule Definition

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

Rationale

A variable with an automatic storage duration is allocated memory at the beginning of an enclosing code block and deallocated at the end. All non-global variables have this storage duration, except those declared static or extern.

Variables with automatic storage duration are not automatically initialized and have indeterminate values. Therefore, you must not read such a variable before you have set its value through a write operation.

Polyspace Implementation

Polyspace® reports a violation of this rule if your code contains these issues:

Troubleshooting

If you expect a rule violation but do not see it, refer to Diagnose Why Coding Standard Violations Do Not Appear as Expected.

Examples

expand all

If command is not 2, the variable val is unassigned. In this case, the return value of function get_sensor_value is undetermined.

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

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

    return val; //Noncompliant              
   
}

If prev is not NULL, the pointer pi is not assigned an address. However, pi is dereferenced on every execution paths, irrespective of whether prev is NULL or not.

#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;
}

Check Information

Group: Initialization
Category: Mandatory
AGC Category: Mandatory

Version History

Introduced in R2014b

expand all