scc

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

commit 83f9c3d38147ea9ed733c49939df819d5aad8732
parent af54b65089b204d8032664acebce17df7efd04d3
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;