This is the mail archive of the gcc@gcc.gnu.org mailing list for the GCC project.


Index Nav: [Date Index] [Subject Index] [Author Index] [Thread Index]
Message Nav: [Date Prev] [Date Next] [Thread Prev] [Thread Next]
Other format: [Raw text]

Re: strict aliasing question


Howard Chu <hyc@highlandsun.com> writes:

> Here's a different example, which produces the weaker warning
>  warning: type-punning to incomplete type might break strict-aliasing rules
> 
> struct foo;
> 
> int blah(int fd) {
>         int buf[BIG_ENOUGH];
>         void *v = buf;
>         struct foo *f;
> 
>         f = v;
>         f = (struct foo *)buf;
> 
>         init(f, fd);
>         munge(f);
>         flush(f);
> }
> 
> "foo" is an opaque structure. We have no idea what's inside, we just
> know that it's relatively small. There are allocators available that
> will malloc them for us, but we don't want to use malloc here because
> it's too slow, so we want to reserve space for it on the stack, do a
> few things with it, then forget it.
> 
> If we go through the temporary variable v, there's no warning. If we
> don't use the temporary variable, we get the "might break" message. In
> this case, nothing in our code will ever dereference the pointer.  Why
> is there any problem here, considering that using the temporary
> variable accomplishes exactly the same thing, but requires two extra
> statements?

Since you don't do any loads or stores via buf, this code is going to
be OK.  The warning you get is not all that good since it gives both
false positives and (many) false negatives.

Your code will be safe on all counts if you change buf from int[] to
char[].  The language standard grants a special exemption to char*
pointers.  Without that exemption, it would be impossible to write
malloc in C.

Ian


Index Nav: [Date Index] [Subject Index] [Author Index] [Thread Index]
Message Nav: [Date Prev] [Date Next] [Thread Prev] [Thread Next]