Is dereferencing invalid pointers legal if no lvalue-to-rvalue conversion occurs

后端 未结 2 1640
伪装坚强ぢ
伪装坚强ぢ 2021-02-05 20:32

Try as I might, the closest answer I\'ve seen is this, with two completely opposing answers(!)

The question is simple, is this legal?

auto p = reinterpre         


        
2条回答
  •  傲寒
    傲寒 (楼主)
    2021-02-05 20:58

    ... some platforms trap on indirection for invalid pointers.

    Most platforms trap on invalid address access. This does not contradict the issue in any way. The question of what happens in *p; boils down to whether an attempt to actually fetch at an invalid address takes place or not.

    The question of fetching is very similar to the core issue 232 (indirection through a null pointer). As you have already pointed out, *p; is a discarded value expression, and as such no lvalue-to-rvalue conversion ("fetching") takes place:

    Tom Plum:

    ...it is only the act of "fetching", of lvalue-to-rvalue conversion, that triggers the ill-formed or undefined behavior.

    And subsequently:

    Notes from the October 2003 meeting:

    We agreed that the approach in the standard seems okay: p = 0; *p; is not inherently an error. An lvalue-to-rvalue conversion would give it undefined behavior.


    As to whether or not reinterpret_cast(0xbadface) produces a valid pointer, indeed in implementations with strict pointer safety, it wouldn't be a safely-derived pointer, and as such is invalid and any use of it is UB.

    But in case of relaxed pointer safety the resulting pointer is valid (otherwise it would be impossible to use pointers returned from binary libraries and components written in C or other languages).

提交回复
热议问题