Main Content

AUTOSAR C++14 Rule A5-3-2

Null pointers shall not be dereferenced

Since R2020b

Description

Rule Definition

Null pointers shall not be dereferenced.

Rationale

Dereferencing a null pointer is undefined behavior. In most implementations, the dereference can cause your program to crash.

Polyspace Implementation

The checker flags pointer dereferences where the pointer might be NULL-valued.

If the issue occurs despite an earlier check for NULL, look for intermediate events between the check and the subsequent dereference. Often the result details (or source code tooltips in Polyspace as You Code) show a sequence of events that led to the defect. You can implement the fix on any event in the sequence. If the result details do not show this event history, you can search for previous references of variables relevant to the defect using right-click options in the source code and find related events. See also Interpret Bug Finder Results in Polyspace Desktop User Interface or Interpret Bug Finder Results in Polyspace Access Web Interface (Polyspace Access).

Extend Checker

A default Bug Finder analysis might not raise a violation of this rule when the input values are unknown and only a subset of inputs can cause an issue. To check for violations caused by specific system input values, run a stricter Bug Finder analysis. See Extend Bug Finder Checkers to Find Defects from Specific System Input Values.

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

#include <iostream>
#include <cstdint>
#include <cstddef>

class A
{
  public:
    A(std::uint32_t a) : a(a) {}
    std::uint32_t GetA() const noexcept
    {
      return a;
    }
  private:
    std::uint32_t a;
};

std::uint32_t Sum(const A* lhs, const A* rhs)
{
  return lhs->GetA() + rhs->GetA(); //Noncompliant
}

A* getAPtr(void); 

int main(void)
{
  A* leftVal = new A(3);
  A* rightVal = getAPtr();
  
  std::uint32_t sum;
  
  if(!rightVal)  {
      sum = Sum(leftVal, rightVal); 
  }
  else 
      sum = 0;

  std::cout << sum << std::endl;
  return 0;
}

In this example, the order of the if and else clause have been switched leading to an accidental null pointer dereference. The variable rightVal is checked for NULL and the NULL-valued of rightVal is used for the subsequent dereference in the function Sum.

Check Information

Group: Expressions
Category: Required, Partially automated

Version History

Introduced in R2020b

expand all