[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index]
bug#15924: [PATCH] dfa: avoid undefined behavior of "1 << 31"
From: |
Paul Eggert |
Subject: |
bug#15924: [PATCH] dfa: avoid undefined behavior of "1 << 31" |
Date: |
Mon, 18 Nov 2013 18:16:10 -0800 |
User-agent: |
Mozilla/5.0 (X11; Linux x86_64; rv:24.0) Gecko/20100101 Thunderbird/24.1.0 |
Jim Meyering wrote:
> static int
> tstbit (unsigned int b, charclass const c)
> {
> - return c[b / INTBITS] & 1 << b % INTBITS;
> + return c[b / INTBITS] & 1U << b % INTBITS;
> }
On a machine with 32-bit int and where b % INTBITS is 31,
the expression c[b / INTBITS] & 1U << b % INTBITS
is of type 'unsigned' and can have the value 2**31, and
this will overflow when tstbit converts that value as an int,
leading to implementation-defined behavior, which can include
raising a signal.
Better would be something like this:
static bool
tstbit (unsigned int b, charclass const c)
{
return c[b / INTBITS] >> b % INTBITS & 1;
}
and it'd probably be better to encourage this style in
other places where the problem occurs, e.g., quotearg.