Safe use of unions



The quoted text below is from comp.std.c which originated
from a discussion on comp.lang.c. I've edited out the parts
that do not apply to my question.

Robert Gamble wrote:
Dann Corbit wrote:
#include <stdio.h>

int main(void)
{
typedef union foo_u {
struct a {
unsigned char carr[sizeof(unsigned int)];
} aa;
struct b {
unsigned int ui;
} bb;
} foo;

foo bar;
bar.bb.ui = 1;
printf("%u\n", (unsigned)bar.aa.carr[0]);
return 0;
}

#include <stdio.h>

int main(void)
{
typedef union foo_u {
unsigned char carr[sizeof(unsigned int)];
unsigned int ui;
} foo;

foo bar;
bar.ui = 1;
printf("%u\n", (unsigned)bar.carr[0]);
return 0;
}

Is the first sample safe but the second not safe?

Neither are safe.

Why is either example unsafe? I understand the output of
the printf calls is unspecified. But I do not see anything
that would be cause for concern other than that.

.



Relevant Pages

  • Re: Safe use of unions
    ... typedef union foo_u { ... struct a { ... unsigned char carr; ... Is the first sample safe but the second not safe? ...
    (comp.lang.c)
  • [tip:x86/urgent] nvram: Fix write beyond end condition; prove to gcc copy is safe
    ... Fix write beyond end condition; prove to gcc copy is safe ... make the logic a bit more explicit so that gcc can statically ... prove that the copy_from_useris safe. ... unsigned char *tmp; ...
    (Linux-Kernel)
  • Re: uchar -> void* -> uchar
    ... So, theoretically, this should be safe. ... I've got the following code that compiles (with warnings), ... void *b = NULL; ...
    (comp.lang.c)
  • Re: char * signedness
    ... is it always safe to pass unsigned char * variables as parameters to ... functions accepting char * arguments? ... For the standard library functions, yes, because while they take char * ... they convert it to unsigned char * internally anyway. ...
    (comp.lang.c)