shithub: scc

Download patch

ref: 83f9c3d38147ea9ed733c49939df819d5aad8732
parent: af54b65089b204d8032664acebce17df7efd04d3
author: Roberto E. Vargas Caballero <k0ga@shike2.com>
date: Wed Mar 30 04:20:49 EDT 2022

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

--- 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 @@
 
 		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;