Re: [PATCH v3 2/2] bsearch: prevent overflow when computing middle comparison element

From: André Goddard Rosa
Date: Wed Nov 11 2009 - 10:01:16 EST


On Tue, Nov 10, 2009 at 10:18 PM, Rusty Russell <rusty@xxxxxxxxxxxxxxx> wrote:
> On Tue, 10 Nov 2009 02:12:31 am André Goddard Rosa wrote:
>> It's really difficult to occur in practice because the sum of the lower
>> and higher limits must overflow an int variable, but it can occur when
>> working with large arrays. We'd better safe than sorry by avoiding this
>> overflow situation when computing the middle element for comparison.
>
> I always thought the obvious answer was:
>
>        mid = start + (end - start)/2;

Hi, Rusty!

Yes, you're right! The previous patch fixes the case where the
number of elements approach the
maximum int value (2^31 - 1 on my computer). If the number of elements
(parameter num) were an
integer amount (Java's array length case), just making those unsigned
would be enough, because
in the worst case we would have:

(max int) * 2 < (max unsigned int)
(2^31 - 1) * 2 < (2^32 - 1)

But it does not fix the case where the number of elements
approaches the maximum unsigned int
value (parameter size_t num).

So, the worst case happens when the number we search for is stored
at the highest extreme of the array.
In that case, 'start' tends toward 'end', and if 'end' is near the
maximum allowed value for a specific data type,
the overflow could still happen.

I'm sending a fixed patch in a moment as per your suggestion.

Thank you,
André
--
To unsubscribe from this list: send the line "unsubscribe linux-kernel" in
the body of a message to majordomo@xxxxxxxxxxxxxxx
More majordomo info at http://vger.kernel.org/majordomo-info.html
Please read the FAQ at http://www.tux.org/lkml/