Dereferencing an invalid pointer, then taking the address of the result

前端 未结 3 2060
抹茶落季
抹茶落季 2020-11-27 07:08

Consider:

int* ptr = (int*)0xDEADBEEF;
cout << (void*)&*ptr;

How illegal is the *, given that it\'s used in conjunct

相关标签:
3条回答
  • 2020-11-27 07:17

    Assuming the variable `ptr' does not contain a pointer to a valid object, the undefined behavior occurs if the program necessitates the lvalue-to-rvalue conversion of the expression `*ptr', as specified in [conv.lval] (ISO/IEC 14882:2011, page 82, 4.1 [#1]).

    During the evaluation of `&*ptr' the program does not necessitate the lvalue-to-rvalue conversion of the subexpression `*ptr', according to [expr.unary.op] (ISO/IEC 14882:2011, page 109, 5.3.1 [#3])

    Hence, it is legal.

    0 讨论(0)
  • 2020-11-27 07:22

    It is legal. Why wouldn't it be? You're just setting a value to a pointer, and then accessing to it. However, assigning the value by hand must be obviously specified as undefined behavior, but that's the most a general specification can say. Then, you use it in some embedded software controller, and it will give you the correct memory-mapped value for some device...

    0 讨论(0)
  • 2020-11-27 07:40

    According to the specification, the effect of dereferencing an invalid pointer itself produces undefined behaviour. It doesn't matter what you do after dereferencing it.

    0 讨论(0)
提交回复
热议问题