Problem with r226035 - in head/usr.bin/grep: . regex?
Benjamin Kaduk
kaduk at MIT.EDU
Wed Oct 5 23:13:50 UTC 2011
On Wed, 5 Oct 2011, Michael Butler wrote:
> On 10/05/11 10:48, I wrote:
>> Does this look right?
>
>> ! ts = ((long)u - v < 0) ? 0 : (u - v); \
>
> Doh! It should probably be ..
>
> ts = ((long)(u - v) < 0) ? 0 : (u - v);
This is definitely incorrect.
Consider the case where u = (int)INT_MAX, v = (int)INT_MIN. Then (u-v) is
evaluated within 'int' width, and overflows, causing undefined behavior
(but probably wrapping), which is then cast to long.
The cases where either u or v are unsigned types can also provide
interesting edge cases. Probably the "most correct" choice is to cast all
values to the widest supported signed integral type (since no type
information is available within the macro scope), including the 'else'
branch of the ternary operator, which is also susceptible to
over/underflow.
There are many style bugs with macros of this nature, on which bde would
presumably be happy to expound.
It seems that (at least in the first usage that I found) 'u' and 'v' are
declared as unsigned int, so casting everything to signed long is unlikely
to introduce breakage in the common case.
-Ben Kaduk
More information about the freebsd-current
mailing list