Main Content

AUTOSAR C++14 Rule A8-5-0

All memory shall be initialized before it is read

Description

Rule Definition

All memory shall be initialized before it is read.

Rationale

The C++ standard does not specify what the value of an uninitialized memory can be. This value is unpredictable and can be different every time the program runs. Reading and using the value of an uninitialized memory results in unexpected behavior.

Polyspace Implementation

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

  • Non-initialized variable: A variable is read before initialization.

  • Non-initialized member: A class member is not initialized in the class constructor:

  • Non-initialized pointer: A pointer is dereferenced before initialization.

Troubleshooting

If you expect a rule violation but Polyspace does not report it, see 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              
   
}

In this example, if flag is not 0, the member _c is not initialized.

The defect appears on the closing brace of the constructor. Following are some tips for navigating in the source code:

  • On the Result Details pane, see which members are not initialized.

  • To navigate to the class definition, right-click a member that is initialized in the constructor. Select Go To Definition. In the class definition, you can see all the members, including those members that are not initialized in the constructor.

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

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: Declarators
Category: Required, Automated

Version History

Introduced in R2019a

expand all