It is required to get the address of a local variable, and save it to the same variable. Is the code correct?

void* p = (void*) &p; 

GCC digests normally. Is UB or strict aliasing violation possible here?

And also in this version:

 int* p = (int*) &p; 

ideone

  • Dunno, but MSVS will probably not let you compile) - Xambey
  • Well, I’d just like the fireman do it not by initialization in the declaration, but by assignment. The rest - "I see no obstacles!" (c) - Harry
  • one
    @Xambey and you try it - VC ++ 2015 is completely calm but compiles ... - Harry
  • @Harry here was a remark that it violates strict aliasing therefore, he doubted. Although I do not see him. - Vladimir Gamalyan
  • ridiculous code)) is it interesting in what cases such tricks would be suitable? - ampawd

1 answer 1

The code for void* correct. the void** type is void** to void* .

Code int* p = (int*) &p; by itself is correct, because although &p is of type int** , but it can be cast to int* via reinterpret_cast (C-style cast in this case).
However, p can not be dereferenced, because this would be a violation of the rules of alising 'a : p actually points to an object of type int* , and the expression *p treats this object as int .

(And of course the result of such a reinterpret_cast cannot be dereferenced due to the rules of the reinterpret_cast itself, but the question was about aliasing .)

  • strict aliasing is it not when two pointers of different types point to the same memory area? - Vladimir Gamalyan
  • one
    @VladimirGamalian here it says that strict aliasing - ru.stackoverflow.com/questions/503265/… . Yes, two pointers to one memory area. - Abyx