[cfe-dev] Unions in the Clang Static Analyzer

Aaron Ballman via cfe-dev cfe-dev at lists.llvm.org
Thu Mar 2 23:12:49 PST 2017


On Thu, Mar 2, 2017 at 8:54 PM, Keno Fischer <keno at juliacomputing.com> wrote:
> This behavior also differs between C and C++. For example, C has explicitly:
>
> [N1570, Footnote 95]
> If the member used to read the contents of a union object is not the
> same as the member last used to store a value in the object, the
> appropriate part of the object representation of the value is
> reinterpreted as an object representation in the new type as described
> in 6.2.6 (a process sometimes called ‘‘type punning’’). This might be
> a trap representation.
>
> where object representation is essentially what you'd get if you
> memcpyed the value.

Yes, if everything lines up just perfectly, then in C this may be
okay. I say may because it can still be a trap representation, it
could be a misaligned access, there could be unspecified values within
the union member, etc (so it depends on the types and the specific
values), so it is *not* strictly a safe operation to do in C either.

~Aaron



More information about the cfe-dev mailing list