This is the mail archive of the
gcc-help@gcc.gnu.org
mailing list for the GCC project.
Re: bad user, or optimization bug with worked-around lvalue casts ?
- From: Andrew Haley <aph at redhat dot com>
- To: Michael Haubenwallner <michael dot haubenwallner at salomon dot at>
- Cc: gcc-help at gcc dot gnu dot org
- Date: Mon, 8 Jan 2007 15:39:50 +0000
- Subject: Re: bad user, or optimization bug with worked-around lvalue casts ?
- References: <1168270540.9287.50.camel@localhost>
Michael Haubenwallner writes:
> Hi,
>
> after switching to gcc-4.1.1 from gcc-3.4.5, I'm facing a problem with
> this code searching for non-blank in a string (extracted test-case):
>
> #include <stdio.h>
> int check(const void *pvBuf)
> {
> for(; *((char*)pvBuf) == ' '; ++ *((char**)&pvBuf));
This is wrong. Try this:
for(; *((char*)pvBuf) == ' '; pvBuf = (char*)pvbuf + 1);
> return *((char*)pvBuf);
> }
> int main(void)
> {
> printf("%d\n", check(" x"));
> return 0;
> }
>
> When building without optimization, it works as expected.
> When building with -O2 or higher, the loop hangs.
> This seems to be platform independant, as it occurs on x86-linux as well
> as powerpc-aix, hppa-hpux, ia64-hpux, x86-solaris and sparc-solaris.
>
> Now the question is:
> Is this a user-bug only, not looking at the output of "-Wall" (because
> this code builds and works successfully for 5 years now),
> or is it a gcc-bug too, producing working code without optimization
> and non-working code with optimization level >= 2 ?
>
> And: can this code be changed without using an intermediate variable ?
This is an aliasing bug. Please see The C standard, Section 6.3.2.3,
Pointers.
Alternatively, you may compile your code with -fno-strict-aliasing.
Andrew.