mirror of
https://github.com/RGBCube/serenity
synced 2025-07-24 14:37:43 +00:00
LibC: bsearch fix for large arrays (#3138)
Implement unsigned arithmetic to compute middle without causing overflow. And without mixed signed/unsigned operations.
This commit is contained in:
parent
bba2da66e7
commit
cdae3f53f1
1 changed files with 9 additions and 10 deletions
|
@ -745,18 +745,17 @@ char* mkdtemp(char* pattern)
|
||||||
|
|
||||||
void* bsearch(const void* key, const void* base, size_t nmemb, size_t size, int (*compar)(const void*, const void*))
|
void* bsearch(const void* key, const void* base, size_t nmemb, size_t size, int (*compar)(const void*, const void*))
|
||||||
{
|
{
|
||||||
int low = 0;
|
char* start = static_cast<char*>(const_cast<void*>(base));
|
||||||
int high = nmemb - 1;
|
while (nmemb > 0) {
|
||||||
while (low <= high) {
|
char* middle_memb = start + (nmemb / 2) * size;
|
||||||
int middle = (low + high) / 2;
|
|
||||||
void* middle_memb = const_cast<char*>((const char*)base + middle * size);
|
|
||||||
int comparison = compar(key, middle_memb);
|
int comparison = compar(key, middle_memb);
|
||||||
if (comparison < 0)
|
if (comparison == 0)
|
||||||
high = middle - 1;
|
|
||||||
else if (comparison > 0)
|
|
||||||
low = middle + 1;
|
|
||||||
else
|
|
||||||
return middle_memb;
|
return middle_memb;
|
||||||
|
else if (comparison > 0) {
|
||||||
|
start = middle_memb + size;
|
||||||
|
--nmemb;
|
||||||
|
}
|
||||||
|
nmemb /= 2;
|
||||||
}
|
}
|
||||||
|
|
||||||
return NULL;
|
return NULL;
|
||||||
|
|
Loading…
Add table
Add a link
Reference in a new issue