C++ Logo

std-discussion

Advanced search

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

From: Myria <myriachan_at_[hidden]>
Date: Mon, 19 Jun 2023 10:43:57 -0700
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.

On Sun, Jun 18, 2023 at 16:07 language.lawyer--- via Std-Discussion <
std-discussion_at_[hidden]> wrote:

> > I'm a bit confused by the OptBool examples from P2641
> > (https://wg21.link/p2641#introduction). The paper claims that both are
> > free from undefined behavior.
> >
> > Reduced case #1:
> >
> > union {
> > bool b = true;
> > char c;
> > } u;
> > +u.c;
> >
> > This reads from an inactive union member of type 'char'. The paper says
> > that this is OK because of [basic.lval]/11.3, but I don't see how it
> > applies here: we're not accessing a 'bool' through a glvalue of type
> > 'char', we're accessing a distinct 'char' object outside its lifetime,
> > which is undefined per [basic.life]/7.1.
> >
> > Reduced case #2:
> >
> > char c;
> > new(&c) bool(true);
> > +c; // #1
> > +(bool&)c; // #2
> >
> > Creating a 'bool' in the storage associated with a 'char' ends the
> > lifetime of the latter ([basic.life]/1.5), meaning #1 once again tries
> > to access an object outside its lifetime. #2 does the same except
> > through a 'bool' glvalue, additionally running afoul of [basic.lval]/11.
> >
> > Is there a mistake in the paper, or am I misunderstanding something?
>
> Your analysis is correct, I've pointed at the same things in Core
> reflector half a year ago, and got no reaction from the authors. Not sure
> what does it mean. 🌚
> --
> Std-Discussion mailing list
> Std-Discussion_at_[hidden]
> https://lists.isocpp.org/mailman/listinfo.cgi/std-discussion
>

Received on 2023-06-19 17:44:11