On Thu, Apr 16, 2026 at 08:03:30PM +1000, Seth McDonald wrote:
> Hi,
> 
> On Thu, 16 Apr 2026 at 11:40:36 +0200, Michal Suchánek wrote:
> > On Thu, Apr 16, 2026 at 11:45:47AM +0300, Evgeniy Berdnikov wrote:
> > >         union { u_char *b; const void *cvoid_b; } ub;
> > > 
> > >         ub.cvoid_b = s;
> > >         u_char *e = ub.b + n;
> > >         while (--e >= ub.b)
> > >                 if (*e == c)
> > >         ...
> > > 
> > >  It assumes that pointers to all bare types are represented identically,
> > >  AFAIK, this is true for all existent C implementations.
> > 
> > Also it breaks the aliasing rules that C fabricates regardless of the
> > actual use of the data.
> 
> Actually in this specific case, it's (almost) fully defined within the C
> standard.  From the C11 spec (the latest I have access to is C11):
> 
> | A pointer to void shall have the same representation and alignment
> | requirements as a pointer to a character type.  Similarly, pointers to
> | qualified or unqualified versions of compatible types shall have the
> | same representation and alignment requirements.
> 
> So the conversion from const void* to void*, and from void* to char*, is
> not undefined behaviour.  As such, if char* was used instead of u_char*
> (which I'm not entirely sure why it isn't already), Evgeniy's workaround
> would be perfectly conformant to the C standard.
> 
> It also doesn't break strict aliasing; unions are explicitly allowed to
> facilitate interpreting the same memory with incompatible types.

The problem is discussed at length eg. here:
https://sqlpey.com/c/c-union-type-punning-behavior-c99-vs-c11-standards-explained/#c-union-type-punning-behavior-c99-vs-c11-standards-explained

In conclusion there is no explicit allowance, and obtuse compiler
writers will intepret different union members as unrelated, and point to
the standard to support such obtuse implementation.

Thanks

Michal


_______________________________________________
isync-devel mailing list
[email protected]
https://lists.sourceforge.net/lists/listinfo/isync-devel

Reply via email to