*BSD News Article 82407


Return to BSD News archive

Path: euryale.cc.adfa.oz.au!newshost.carno.net.au!harbinger.cc.monash.edu.au!munnari.OZ.AU!news.ecn.uoknor.edu!solace!news.stealth.net!www.nntp.primenet.com!nntp.primenet.com!howland.erols.net!sol.ctr.columbia.edu!startide.ctr.columbia.edu!wpaul
From: wpaul@ctr.columbia.edu (Bill Paul)
Newsgroups: comp.unix.bsd.freebsd.misc
Subject: Re: Compiler bug?
Date: 6 Nov 1996 16:21:45 GMT
Organization: Columbia University Center for Telecommunications Research
Lines: 47
Message-ID: <55qdup$8jv@sol.ctr.columbia.edu>
References: <55p7ck$r2l@csgrad.cs.vt.edu>
NNTP-Posting-Host: startide.ctr.columbia.edu
X-Newsreader: TIN [version 1.2 PL2]

Daring to challenge the will of the almighty Leviam00se, Tommy Johnson
(tjohnson@csgrad.cs.vt.edu) had the courage to say:

: This program doesn't work as I think it should.   On line 10, b is not 
: incremented between the first and second b++'s, though it is correct
: after the entire expression.

: On FreeBSD 2.2-Current as of about Oct 13, the program below produces
: 0x1212 instead of 0x3412  (gcc 2.7.2.1, or gcc 2.6.3).  It also happens
: on NetBSD 1.1B as of about May 16 on an HP300 (gcc 2.7.2).  It DOES produce
: 0x3412 on a DEC alpha with gcc 2.7.2, or gcc 2.7.2 on a DECstation
: (OSF1 3.2 148, and Ultrix 4.4 rev 69 respectively).

: (It also breaks on FreeBSD 2.1.5-Release with gcc 2.6.3)

: Am I hallucinating?   TIA...

[chop]
:         a=c[b++]|((c[b++])<<8);
[chop]

I believe you have invoked undefined compiler behavior with this code.
It is therefore not a bug that the result differs from one implementation
to another: undefined behavior means that the compiler can do anything
that it wants, up to and including reformatting all your disk drives and
setting fire to your house.

(No, I can't quote the exact part of the ANSI spec that says this code
is bogus; I just know that it is.)

You need to rewrite your code so that you do not have two b++'s in the
same statement; then it should behave the same regardless of the platform
or compiler. This should as you expect:

a = c[b++];
a |= ((c[b++])<<8);

-Bill

--
=============================================================================
-Bill Paul            (212) 854-6020 | System Manager, Master of Unix-Fu
Work:         wpaul@ctr.columbia.edu | Center for Telecommunications Research
Home:  wpaul@skynet.ctr.columbia.edu | Columbia University, New York City
=============================================================================
 "If you're ever in trouble, go to the CTR. Ask for Bill. He will help you."
=============================================================================