scc

simple c99 compiler
git clone git://git.simple-cc.org/scc
Log | Files | Refs | Submodules | README | LICENSE

commit 06481dfcae174387b91a2dbc80ff2c48b5e305fc
parent e2a1ec076c6543aacae71a150c198c705db08a68
Author: Roberto E. Vargas Caballero <k0ga@shike2.com>
Date:   Wed, 30 Mar 2022 08:20:49 +0200

libc/search: Test for overflow and underflow cases

There are 2 special cases that could generate problems in the code:

	- t < 0 and mid == 0: This case would generate a wrap around
	  that likely will stop the loop.

The patch adds tests in both cases to make the code more orthogonal
and readable, even when the second test is not strictly needed.
	  and since size_t is unsigned the test would fail.
	- t > 0 and mid == SIZE_MAX: This case would generate a wrap around

Diffstat:
Msrc/libc/stdlib/bsearch.c | 7+++++--
1 file changed, 5 insertions(+), 2 deletions(-)

diff --git a/src/libc/stdlib/bsearch.c b/src/libc/stdlib/bsearch.c @@ -1,3 +1,4 @@ +#include <stdint.h> #include <stdlib.h> void * @@ -16,10 +17,12 @@ bsearch(const void *key, const void *ary, size_t n, size_t size, if ((t = (*cmp)(key, cur)) == 0) return cur; - else if (t > 0) + else if (t > 0 && mid < SIZE_MAX) low = mid + 1; - else + else if (t < 0 && mid > 0) high = mid - 1; + else + break; } return NULL;