Main Content

MISRA C++:2023 Rule 8.2.5

reinterpret_cast shall not be used

Since R2024b

Description

Rule Definition

reinterpret_cast shall not be used.

Rationale

The operator reinterpret_cast allows casting between unrelated types, which can lead to undefined behavior. To avoid undefined behavior, do not use reinterpret_cast.

As an exception, reinterpret_cast is allowed in these cases because the behavior of these conversions are well-defined:

  • Casting a pointer to T*, where T is one of void, char, unsigned char, or std::byte, with cv qualification.

  • Converting a pointer p to an integer that is large enough to represent a pointer value, such as std::uintptr_t.

Polyspace Implementation

Polyspace® reports a violation of this rule on use of the reinterpret_cast operator. As exceptions, these uses are not reported as violations:

  • reinterpret_cast<T*> where T is one of void, char, unsigned char or std::byte.

  • reinterpret_cast<T>(p) where p is a pointer and T is an integer that is large enough to represent a pointer value.

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

This example shows that reinterpret_cast can convert between unrelated types such as A* and uint32_t*. Converting between such unrelated types results in undefined behavior. Polyspace reports violations of this rule on such uses.

#include <cstdint>
#include <array>
class A {};
void foo(A* p1) {
	uint32_t *p2 = reinterpret_cast< uint32_t * >(p1);    //Noncompliant
}

void bar(uint8_t* p1) {
	uint32_t *p2 = reinterpret_cast< uint32_t * >(p1);    //Noncompliant
}

template <class T>
void mycast(T* pt) {
	auto pbx = reinterpret_cast< T const * >(pt);

}

void func() {
	float x;
	mycast<std::byte>(&x); //Compliant by exception
	mycast<void*>(&x);//Compliant by exception
	mycast<char*>(&x);//Compliant by exception
	mycast<unsigned char*>(&x);//Compliant by exception
	mycast<int> (&x); //Noncompliant
}

As an exception, using reinterpret_cast is allowed in cases where the behavior is defined. The function func() shows such compliant use cases.

Check Information

Group: Expressions
Category: Required

Version History

Introduced in R2024b