7

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.

5
  • Using both GCC and Clang (trunk builds), building and running with extra warnings enabled and UB sanitizer sanitizer says it's okay (see on the compiler explorer). But it sure does look fishy, and if it looks fishy then I would not want to touch such code with a ten-foot pole. Don't do this! Commented Jun 28, 2021 at 11:37
  • did you actually need to do that? or is just curiosity? Commented Jun 28, 2021 at 12:05
  • Why leave the dereferencing of the pointer out of the question? I don't think it's a problem in this case. If you go to all that effort to create the pointer you might as well try and use it. Commented Jun 28, 2021 at 12:07
  • 1
    @Ivan, Yes, I need. I'm making C++ wrapper for GLib/GStreamer. My top base class has void* member. In derived classes I need to cast this member to reference to specific pointer. I can't cast pointer by value because this. I need exactly reference. Commented Jun 28, 2021 at 12:13
  • Please ask about your actual problem that you're trying to solve, and tell us the solution you want to use and what problems you havw with this solution. Asking directly about your problem gives us more context and better chance of helping you solve that actual problem, than the rather context-less question you have here. You might want to refresh the help pages, take the SO tour, read How to Ask, as well as this question checklist. Commented Jun 28, 2021 at 13:01

2 Answers 2

2

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.

Sign up to request clarification or add additional context in comments.

Comments

0

In this absolutely specific case without deferencing it should be okay I think. I verified pointer value. It's different story when sizeof(void*) and sizeof(int*) are different (although I do not know whether that is even possible).

By doing this, you are taking complete responsibility of very known scenario.

   int   i = 5;
   void *p = &i; //convert int* => void*


   int* &r = reinterpret_cast<int* &>(p); //convert void* which was int* to int*&
   int*  p2 = r; //**copy** address stays same

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.