summaryrefslogtreecommitdiff
path: root/src/stdlib/bsearch.c
diff options
context:
space:
mode:
authorJakob Kaivo <jkk@ung.org>2024-01-31 22:23:31 -0500
committerJakob Kaivo <jkk@ung.org>2024-01-31 22:23:31 -0500
commit473a9dae23d46a4ec1827e4d68363eea805c08dc (patch)
tree7e7bd01cc492be6b01f3a26c747a1a79b9ef95a0 /src/stdlib/bsearch.c
parent656d95bc6b5a2c55c79b07a70661137ea55cb0b4 (diff)
check for UB in qsort() and bsearch()
Diffstat (limited to 'src/stdlib/bsearch.c')
-rw-r--r--src/stdlib/bsearch.c12
1 files changed, 10 insertions, 2 deletions
diff --git a/src/stdlib/bsearch.c b/src/stdlib/bsearch.c
index c710406e..a096cf16 100644
--- a/src/stdlib/bsearch.c
+++ b/src/stdlib/bsearch.c
@@ -1,4 +1,5 @@
#include <stdlib.h>
+#define NEED_COMPAR
#include "_stdlib.h"
/** binary search **/
@@ -14,13 +15,20 @@ void * bsearch(const void * key, const void * base, size_t nmemb, size_t size, i
SIGNAL_SAFE(0);
ASSERT_NONNULL(key);
ASSERT_NONNULL(base);
- /* overlap can't be detected because the size of key can't be known */
+ /* assume that key exists in base, don't check for overlap */
/* TODO: ensure everything is in order to start with */
+ #ifndef NDEBUG
+ for (size_t i = 0; nmemb != 0 && i < nmemb - 1; i++) {
+ if (SAFE_COMPAR(compar, addr + (i * size), addr + ((i + 1) * size), size, "bsearch") > 0) {
+ __undefined("In call to bsearch(): Base array is not sorted");
+ }
+ }
+ #endif
while (ret == NULL) {
/* TODO: ensure compar doesn't modify things */
- int comp = compar(key, addr + (i * size));
+ int comp = SAFE_COMPAR(compar, key, addr + (i * size), size, "bsearch");
if (comp == 0) {
return (void*)(addr + (i * size));
} else if (comp > 0) {