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
You take &v1
into c.p and later using operator ++ you advance it. You cannot rely on the ordering of the stack, therefore comes undefined behavior ((&v1)+1 != &v2
)
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.
It doesn't have to be UB or compiler bug. It can be neither due to the way that VS2010 was produced.
Strictly speaking, your program exhibits well-defined behaviour. However, that might only be according to the newest C++ Standard. VS2010 is only implemented against a draft Standard which may not have included this provision. If it did not, then your code is not UB, but VS is not incorrect to produce UB, as those were the requirements of the time it was made.
Of course, if it's been legal to treat stack objects as an array of one object in C++03, then it is a compiler bug.
Edit: If you still get the crash for an array as you state, then that is definitely a compiler bug.