The subtraction is removed at the expense of generality: when the element size
is 1, the array length cannot exceed half the architecture's addressable
memory.

Signed-off-by: Wedson Almeida Filho <wedso...@gmail.com>
---
 lib/bsearch.c |    7 ++++++-
 1 file changed, 6 insertions(+), 1 deletion(-)

diff --git a/lib/bsearch.c b/lib/bsearch.c
index e33c179..668ae6c 100644
--- a/lib/bsearch.c
+++ b/lib/bsearch.c
@@ -24,6 +24,11 @@
  * contents of the array should already be in ascending sorted order
  * under the provided comparison function.
  *
+ * There is a limitation when @size is 1: in this case @num must be at
+ * most SIZE_MAX / 2; that is, the number of elements in the sorted
+ * array must be at most half the maximum number expressible as a size_t
+ * to avoid overflows.
+ *
  * Note that the key need not have the same type as the elements in
  * the array, e.g. key could be a string and the comparison function
  * could compare the string with the struct's name field.  However, if
@@ -37,7 +42,7 @@ void *bsearch(const void *key, const void *base, size_t num, 
size_t size,
        int result;
 
        while (start < end) {
-               size_t mid = start + (end - start) / 2;
+               size_t mid = (start + end) / 2;
 
                result = cmp(key, base + mid * size);
                if (result < 0)
-- 
1.7.9.5

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

Reply via email to