Main Content

MISRA C++:2023 Rule 8.2.7

A cast should not convert a pointer type to an integral type

Since R2024b

Description

Rule Definition

A cast should not convert a pointer type to an integral type.

Rationale

The C++ standard specifies only the minimum size required for integral types. The implemented size of integral types and pointers depends on your hardware and development environment. In an environment where pointers have a larger size than integral types, casting a pointer type to an integral type results in an overflow. Avoid casting pointers to integral types.

Polyspace Implementation

Polyspace® flags a casting operation if it converts a pointer type variable to an integral type variable.

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

void foo(){
	int* pInt;
	//...
	int address = reinterpret_cast<int>(pInt);//Noncompliant
}

In this example, the pointer pInt is cast to an int. Depending on your environment, this operation might result in an overflow. For instance, in a 64-bit system, the size of pInt might be 64-bit and the size of address might be 32-bit. Polyspace flags this casting operation.

Check Information

Group: Expressions
Category: Advisory

Version History

Introduced in R2024b