This is the mail archive of the 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]

Re: finding strict aliasing problems

> One thing I do *not* want to do is start a repeat of
> the 1999 discussion.

Too late. :-)

> So, there are some obvious aliasing problems with this code
> (especially in the bignum code, where the bignum digits are
> accessed either as 64-bit unsigned ints or 16-bit unsigned ints).
> But is this a problem?
> #include <stdlib.h>
> #include <stdio.h>
> void
> foo (long int x)
> {
>   printf("%d %f\n", *((int *) x), *(double *) (((int *) x) + 1));
> }
> int
> main()
> {
>   long int x = (long int) malloc (sizeof(int)+sizeof(double));
>   *(int *)x = 1;
>   *(double *) (((int *) x) + 1) = 2.0;
>   foo(x);
>   return 1;
> }
> Here, each word of memory is accessed either as double or
> int, but not both, even though to get to a valid double pointer
> I need to increment the int pointer.  Is this OK?

Well, assuming that your processor does not require 8-byte alignment
of doubles ....

The compiler is allowed to assume that accesses through int pointers
never collide with double pointers, so code slightly different from
this would be illegal.  But, as you say, in this case there is no
aliasing.  Just the same, anyone who writes this type of code is
probably going to write other, similar code that will malfunction
is -fstrict-aliasing is set.

A less risky and easier to maintain style would be to always use
char arrays to store mixed memory like this.  Claiming that the real
type is long int for memory where you store doubles is IMHO a design
mistake, because it makes it very likely that bad code (in the sense of
the ISO C standard and -fstrict-aliasing) will be written.

> Compiled with yesterday's 3.1 with -Wall -W without any warnings.

That doesn't mean anything, the compiler does not have warnings AFAIK
that say anything about possible aliasing violations (though there
was discussion of implementating some warnings in the past).  You only
find out when your program doesn't work.

(Just to head off the flamers who weren't around two years ago: if
-fstrict-aliasing alters the behavior of your program, there are many
C compilers besides GCC that will produce bad code as well.  The
aliasing rules are in the standard).

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