This rule is part of MISRA C++:2023.
Usage of this content is governed by Sonar’s terms and conditions. Redistribution is
prohibited.
Rule 8.2.6 - An object with integral, enumerated, or pointer to void type shall not be cast to a pointer type
[expr.reinterpret.cast] Unspecified 7
[expr.static.cast] Undefined 12; Unspecified 13
Category: Required
Analysis: Decidable,Single Translation Unit
Amplification
This rule does not apply:
- When the destination type is a pointer to function type or a pointer to member function type (see M23_091: MISRA C++ 2023
Rule 8.2.4); or
- For casts between pointers to
void, regardless of any cv-qualification.
Rationale
Casting from either an integral type or a pointer to void type to a pointer to an object may lead to unspecified
behaviour.
A round trip conversion of a pointer to object type through void * (T * -> void * -> T *) is well-defined. However,
this is prohibited by this rule as it is error prone and the detection of any error would be undecidable.
Note: casting from an integer to a pointer may be unavoidable when addressing memory mapped registers or other hardware specific
features.
Example
struct S
{
int32_t i;
int32_t j;
};
void f ( void * p1, int32_t i )
{
S * s1 = static_cast< S * >( p1 ); // Non-compliant
S * s2 = reinterpret_cast< S * >( i ); // Non-compliant
void * p2 = reinterpret_cast< void * >( i ); // Non-compliant
auto p3 = const_cast< void const * >( p2 ); // Compliant
}
Copyright The MISRA Consortium Limited © 2023