Crash in C++ code due to undefined behaviour or compiler bug?

后端 未结 3 1990
夕颜
夕颜 2021-02-19 01:15

I am experiencing strange crashes. And I wonder whether it is a bug in my code, or the compiler. When I compile the following C++ code with Microsoft Visual Studio 2010 as an op

3条回答
  •  暖寄归人
    2021-02-19 01:32

    The code is fine. It's a compiler bug.

    The code *(c++) = v2 will post-increment c.p yielding the original value. That value was assigned in the previous line and is &v1. So, in effect, it does v1 = v2;, which is perfectly fine.

    c.p now behaves as a one-past-the-end of a one element array that holds only v1, per §5.7p4 of the standard:

    For the purposes of these operators [+ and -], a pointer to a nonarray object behaves the same as a pointer to the first element of an array of length one with the type of the object as its element type.

    Then *(--c) moves that pointer back to &v1 and dereferences it, which is also fine.

提交回复
热议问题