>
>
>
V1091. The pointer is cast to an intege…


V1091. The pointer is cast to an integer type of a larger size. Casting pointer to a type of a larger size is an implementation-defined behavior.

The analyzer has detected that a pointer is cast to an integer type of a larger size. The result may differ from a programmer's expectation.

According to C and C++ standards, the result of such an expression is implementation-defined. In most implementations the programmer will get the expected result when a pointer is cast to an integer type of the same size.

Consider the following synthetic example:

void foo()
{
  const void *ptr = reinterpret_cast<const void *>(0x80000000);
  uint64_t ui64 = reinterpret_cast<uint64_t>(ptr); // <=
}

The 'ptr' pointer is converted to the 'uint64_t' type with size of 8 bytes. On 32-bit platforms, the size of pointers is 4 bytes. The result of such casting depends on the implementation of the compiler.

So, if the GCC or MSVC compiler is used, the value 0xffff'ffff'8000'0000 will be written to the 'ui64' variable. Meanwhile, Clang will write the value 0x0000'0000'8000'0000.

To convert a 32-bit pointer to a 64-bit integer and avoid the implementation-defined behavior, do the following:

  • Convert a 32-bit pointer to a 32-bit integer
  • Convert the resulting 32-bit integer to a 64-bit integer

To fix the code above, we first convert the pointer to the 'uintptr_t' type. This is the unsigned integer type whose size is always equal to the pointer size. Then we convert the resulting 32-bit integer to the 64-bit integer. Here's the corrected code:

void foo()
{
  const void *ptr = reinterpret_cast<const void *>(0x80000000);
  uint64_t ui64 = static_cast<uint64_t>(reinterpret_cast<uintptr_t>(ptr));
}

This diagnostic is classified as: