Suggested warning: "negating an expression of unsigned type does not yield a negative value"
Falk Hueffner
falk.hueffner@student.uni-tuebingen.de
Mon Oct 6 16:11:00 GMT 2003
Joe Buck <jbuck@synopsys.com> writes:
> On Mon, Oct 06, 2003 at 02:46:43PM +0200, Falk Hueffner wrote:
> > I just found yet another bug of the kind:
> >
> > int f (int *p, unsigned x) { return p[-x]; }
> >
> > which only manifests on 64 bit platforms, because most (all?)
> > platforms have wrapping address arithmetic.
>
> The C and C++ standards require that unsigned values obey modulo 2**N
> arithmetic, so the value of -x is rigorously defined.
Sure it is. But it is not what is intended. Example: x = 5, then
-x=4294967291, i.e., p will be advanced by 4294967291 bytes, which is
way beyond the legal range of p, but happens to work anyway on 32 bit
architectures (but not on 64 bit architectures).
> > char *namestart;
> > size_t namelen;
> > [...]
> > for (namelen = 1; !ISSPACE (namestart[-namelen]); namelen++)
> >
> > This looks actually invalid to me, although it will probably work
> > everywhere.
>
> It's valid everywhere.
I'm pretty sure it's not. -namelen is, again, something like
4294967291 (or 18446744073709551611), which is not a legal array
index.
> > In fold_const.c, there's
> >
> > case RSHIFT_EXPR:
> > int2l = -int2l;
> >
> > also "invalid but works" since it's later passed to a function taking
> > int.
>
> Again, this is valid everywhere.
No, this produces an unsigned value which cannot be represented in a
signed value of same width, but is converted to signed, which is
undefined according to the standard.
> > Then there's everybody's favourite idiom "x &= -x", but it can be
> > expressed clearer as "x &= ~x + 1".
>
> Again, it's fine as is.
I agree with that.
--
Falk
More information about the Gcc
mailing list