Re: Neatest way to get the end pointer?



On Feb 12, 8:38 am, r...@xxxxxxxxxxxxxxxxxxxxxx (Richard Bos) wrote:
"Chris Thomasson" <cris...@xxxxxxxxxxx> wrote:
"Tomás Ó hÉilidhe" <t...@xxxxxxxxxxx> wrote in message
I was referring to the rule whereby you can't write to union member A
and then go on to read from union member B.

I have always wondered why that rule exists. For instance:
typedef union foo_u {
long int a;
int b;
} foo;
foo f = { 0 };
f.a = 1;
printf("%d\n", f.b);

Possibly because it is hard to write a rule which reliably forbids the
kind of union hacks which would break, but allows the ones that
wouldn't, while the kind of aliasing hackery which one can do with
unions is also done, and more reliably, with pointer aliasing.

It's not true. Some TC explicitly made type punning using
unions work (unless you step onto a trap representation),
while pointer aliasing is UB. And here's UB in action:

muntyan@munt10:/tmp$ cat alias.c
#include <stdio.h>

int func (void)
{
int f = 9;
*(short*)&f = 2;
return f;
}

int main (void)
{
printf ("%d\n", func());
return 0;
}

muntyan@munt10:/tmp$ gcc -O2 -Wall alias.c
alias.c: In function 'func':
alias.c:6: warning: dereferencing type-punned pointer will break
strict-aliasing rules

muntyan@munt10:/tmp$ ./a.out
9

Yevgen
.



Relevant Pages

  • (long) An AES implementation for 32-bit platforms
    ... union BLOCK ... needed in the AES algorithm. ... typedef unsigned int word; ... void computetables() ...
    (sci.crypt)
  • Re: Unions Redux
    ... union {int s; unsigned int us;} u; ... depends on the object representation compatibility, ... all to do with the fact that there is a union involved. ... is a trap representation for signed int. ...
    (comp.lang.c)
  • Re: Nesting dis-similar hierarchies
    ... create table Teams(TeamIndex int, ReqTeamName varchar(5), TeamNumber int) ... UNION ... TeamIndex, ReqTeamName, TeamNumber, ...
    (microsoft.public.sqlserver.xml)
  • Re: problem with cast and unions
    ... The part where there is that problem is about conversion from a C float ... to a Small "cell" (actually an int). ... structure, and even then, only if it was NOT the member most recently ... need to declare the union. ...
    (comp.lang.c)
  • Re: void * pointer convert problem.
    ... >> int year; ... unions: if a union contains several structures that share a common ... _common initial sequence_ if corresponding members have compatible ...
    (comp.lang.c)