This is the mail archive of the
mailing list for the GCC project.
Re: finding strict aliasing problems
- To: lucier at math dot purdue dot edu (Brad Lucier)
- Subject: Re: finding strict aliasing problems
- From: Joe Buck <jbuck at racerx dot synopsys dot com>
- Date: Wed, 2 May 2001 00:06:04 -0700 (PDT)
- Cc: gdr at codesoucery dot com (Gabriel Dos Reis), mrs at windriver dot com (Mike Stump), jakub at redhat dot com, feeley at iro dot umontreal dot ca, gcc at gcc dot gnu dot org, lucier at math dot purdue dot edu
> 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>
> foo (long int x)
> printf("%d %f\n", *((int *) x), *(double *) (((int *) x) + 1));
> long int x = (long int) malloc (sizeof(int)+sizeof(double));
> *(int *)x = 1;
> *(double *) (((int *) x) + 1) = 2.0;
> 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).