AutosarC++19_03-A5.2.4

reinterpret_cast shall not be used

Required inputs: IR

Rationale

Use of reinterpret_cast may violate type safety and cause the program to access a variable as if it were of another, unrelated type.

Example
// $Id: A5-2-4.cpp 289436 2017-10-04 10:45:23Z michal.szczepankiewicz $
    #include <cstdint>
    #include <string>
    void F1() noexcept
    {
          std::string str = "Hello";
          std::int32_t* ptr = reinterpret_cast<std::int32_t*>(&str);       // Non-compliant
    }
    struct A
    {
         std::int32_t x;
         std::int32_t y;
    };
    class B
    {
       public:
         virtual ~B() {}

        private:
          std::int32_t x;
    };
    class C : public B
    {
    };
    class D : public B
    {
    };
    void F2(A* ptr) noexcept
    {
        B* b1 = reinterpret_cast<B*>(ptr); // Non-compliant
        std::int32_t num = 0;
        A* a1 = reinterpret_cast<A*>(num); // Non-compliant
        A* a2 = (A*)
             num; // Compliant with this rule, but non-compliant with Rule A5-2-2.
        B* b2 = reinterpret_cast<B*>(num); // Non-compliant
        D d;
        C* c1 = reinterpret_cast<C*>(&d); // Non-compliant - cross cast
        C* c2 = (C*)&d; // Compliant with this rule, but non-compliant with Rule
                         // A5-2-2. Cross-cast.
        B* b3 = &d;      // Compliant - class D is a subclass of class B
    }
See Also
  • MISRA C++ 2008 [7]: Rule 5-2-7 An object with pointer type shall not be converted to an unrelated pointer type, either directly or indirectly.
  • C++ Core Guidelines [11]: Type.1: Don’t use reinterpret_cast.

Possible Messages

Key

Text

Severity

Disabled

reinterpret_cast

reinterpret_cast should not be used.

None

False

Options

allow_cast_of_pointer_sized_integers

allow_cast_of_pointer_sized_integers : bool = False

Allow reinterpret_cast to cast to an integer type large enough to represent a pointer value.
 

allow_cast_to_type

allow_cast_to_type : set[bauhaus.analysis.config.QualifiedName] = set()

A set of full qualified type names for those pointer types that reinterpret_cast are allowed to cast to.