Web lists-archives.com

Re: Strict aliasing, yes or no?

On Wed, 19 Apr 2017 12:21:06 +0100
Simon McVittie <smcv@xxxxxxxxxxxxx> wrote:
> On Tue, 18 Apr 2017 at 23:05:04 +0100, Daniel Boles wrote:
> > Well, technically, code that relies on aliasing is
> > inherently buggy from the outset, because that violates the
> > standard.  
> Not relying on aliasing forbids casting between dissimilar types,
> which rules out "normal" C tricks like casting between GArray and
> GRealArray (where GRealArray starts with the same members as GArray)
> as a way to have a partially-opaque struct, or an
> opaque-other-than-size struct on the stack; so regardless of whether
> it might be desirable to be writing Standard C, I'm not sure that
> GLib can do that without breaking its API.

That (GArray to GRealArray) does break the strict aliasing rules, unless
done through a union (OK with unions in C99 with Technical Corrigendum 3
and in C11, implementation defined only in C89, but fine with gcc and

I think most reasonable C programmers have roughly got to grips with
strict aliasing now.  Presumably this dates back to less illuminated
> It is also not particularly clear from ISO/IEC 9899:201x draft N1570
> (which is essentially the same document as Standard C, but without the
> price tag) whether the usual C pseudo-object-orientation idiom[1]
> (which is a fairly fundamental part of GObject) is considered to be
> valid in Standard C.

That is and always has been perfectly valid C.  You can always cast a
pointer to one type to a pointer to the effective type of the pointee
and dereference it.  It so happens that the initial address of a struct
has two effective types in C, that of the struct itself and that of its
first member, which are required to have the same address.  You don't
even need to rely on the fifth bullet of §6.5/7 of C11 - it is covered
by the basic proposition in the first bullet.

gtk-devel-list mailing list