C++ Logo

std-discussion

Advanced search

Re: UB in P2641 'Checking if a union alternative is active'

From: Matthew House <mattlloydhouse_at_[hidden]>
Date: Mon, 19 Jun 2023 15:02:29 -0400
On Mon, Jun 19, 2023 at 1:56 PM Marcin Jaczewski via Std-Discussion
<std-discussion_at_[hidden]> wrote:
>
> pon., 19 cze 2023 o 19:44 Myria via Std-Discussion
> <std-discussion_at_[hidden]> napisał(a):
> >
> > And yet ironically:
> >
> > char *p = &u.c;
> > char *q = reinterpret_cast<char*>(&u);
> > assert(p == q); // succeeds
> > u.b = true;
> > +*p; // undefined behavior
> > +*q; // OK
> >
> > …I think.
> >
>
> Maybe instead of `char` it should be `char[1]`? Then because of array
> decay all access will be by
> pointer to char and this should be defined behavior.

`char c[1];` still doesn't work: the decayed pointer is still a
pointer to the first element of the inactive `u.c` object, rather than
a pointer to the active `u.i` object or entire `u` object, as with `q`
in this example.

Received on 2023-06-19 19:02:42