Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is using reference to pointer that was casted with reinterpret_cast undefined behavior?

Is the following code UB?

int   i  = 5;
void *p  = &i;

int* &r  = reinterpret_cast<int* &>(p);
int*  p2 = r;

Please note I do not dereference pointer.

like image 955
anton_rh Avatar asked Jun 28 '21 11:06

anton_rh


People also ask

What does Reinterpret_cast mean in C++?

The reinterpret_cast allows the pointer to be treated as an integral type. The result is then bit-shifted and XORed with itself to produce a unique index (unique to a high degree of probability). The index is then truncated by a standard C-style cast to the return type of the function.

What is the purpose of Reinterpret_cast and how does it differ from a regular cast?

reinterpret_cast is a type of casting operator used in C++. It is used to convert a pointer of some data type into a pointer of another data type, even if the data types before and after conversion are different. It does not check if the pointer type and data pointed by the pointer is same or not.

Is Reinterpret_cast safe?

the result of a pointer-to-pointer reinterpret_cast operation can't safely be used for anything other than being cast back to the original pointer type.


Video Answer


1 Answers

Yes, it is UB.

reinterpret_cast<int* &>(p);

is equivalent to

*reinterpret_cast<int**>(&p);

reinterpret_cast of void** to int** is allowed, but the implicit dereference is UB because the type of data (void*) and the type it is being accessed as (int*) are not similar.

like image 149
Jeff Garrett Avatar answered Sep 22 '22 06:09

Jeff Garrett