Messages in this thread Patch in this message | | | From | Wedson Almeida Filho <> | Subject | [PATCH v2] lib: One less subtraction in binary search iterations. | Date | Mon, 8 Jul 2013 23:37:02 -0700 |
| |
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 <wedsonaf@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
| |