Main Content

MISRA C++:2023 Rule 8.2.8

An object pointer type shall not be cast to an integral type other than std::uintptr_t or std::intptr_t

Since R2024b

Description

Rule Definition

An object pointer type shall not be cast to an integral type other than std::uintptr_t or std::intptr_t.

Rationale

The C++ standard guarantees that the types std::uintptr_t and std::intptr_t accommodate all possible values of a pointer. Other integral types cannot accommodate all possible values of a pointer. Casting a pointer to an integral type other than std::uintptr_t or std::intptr_t can result in unexpected behavior.

To comply with this rule, use the type std::uintptr_t or std::intptr_t in the cast expression explicitly.

Polyspace Implementation

Polyspace® reports a violation of this rule if both of these conditions are true:

  • You cast a pointer to an integral type, either using a cast operator or by using C-style casts.

  • The cast expression does not explicitly use the types std::uintptr_t or std::intptr_t.

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

In this example, a pointer to the struct type S is cast to an integral type.

#include <cstdint>
struct S {
};

template<typename T>
void foo(S *s) {
	auto p = reinterpret_cast<T>(s); // Noncompliant

	auto r = (std::uint64_t)s; //Noncompliant
	//...
}

void bar(S *s) {
	foo<std::intptr_t>(s);
	auto a = (std::intptr_t)s; //Compliant

}

In the function template foo(), the pointer s is cast into different types, but not explicitly cast into the types std::uintptr_t or std::intptr_t. Polyspace reports violations on these casts. In the function bar(), the pointer s is explicitly cast into std::intptr_t. This conversion is compliant.

Check Information

Group: Expressions
Category: Required

Version History

Introduced in R2024b