C++ Logo

std-discussion

Advanced search

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

From: Marcin Jaczewski <marcinjaczewski86_at_[hidden]>
Date: Mon, 19 Jun 2023 19:56:17 +0200
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.

> 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
>
> --
> Std-Discussion mailing list
> Std-Discussion_at_[hidden]
> https://lists.isocpp.org/mailman/listinfo.cgi/std-discussion

Received on 2023-06-19 17:56:29