Welcome to mirror list, hosted at ThFree Co, Russian Federation.

git.kernel.org/pub/scm/git/git.git - Unnamed repository; edit this file 'description' to name the repository.
summaryrefslogtreecommitdiff
diff options
context:
space:
mode:
authorDerrick Stolee <dstolee@microsoft.com>2017-10-08 21:29:37 +0300
committerJunio C Hamano <gitster@pobox.com>2017-10-10 02:57:24 +0300
commit19716b21a4255ecc7148b54ab2c78039c59f25bf (patch)
tree5f1cecbffc543c64e7c4c4f371d204424e1ce1bb /sha1-lookup.c
parent217f2767cbcb562872437eed4dec62e00846d90c (diff)
cleanup: fix possible overflow errors in binary search
A common mistake when writing binary search is to allow possible integer overflow by using the simple average: mid = (min + max) / 2; Instead, use the overflow-safe version: mid = min + (max - min) / 2; This translation is safe since the operation occurs inside a loop conditioned on "min < max". The included changes were found using the following git grep: git grep '/ *2;' '*.c' Making this cleanup will prevent future review friction when a new binary search is contructed based on existing code. Signed-off-by: Derrick Stolee <dstolee@microsoft.com> Reviewed-by: Jeff King <peff@peff.net> Signed-off-by: Junio C Hamano <gitster@pobox.com>
Diffstat (limited to 'sha1-lookup.c')
-rw-r--r--sha1-lookup.c4
1 files changed, 2 insertions, 2 deletions
diff --git a/sha1-lookup.c b/sha1-lookup.c
index 2552b7902c..4cf3ebd921 100644
--- a/sha1-lookup.c
+++ b/sha1-lookup.c
@@ -10,7 +10,7 @@ static uint32_t take2(const unsigned char *sha1)
* Conventional binary search loop looks like this:
*
* do {
- * int mi = (lo + hi) / 2;
+ * int mi = lo + (hi - lo) / 2;
* int cmp = "entry pointed at by mi" minus "target";
* if (!cmp)
* return (mi is the wanted one)
@@ -95,7 +95,7 @@ int sha1_pos(const unsigned char *sha1, void *table, size_t nr,
hi = mi;
else
lo = mi + 1;
- mi = (hi + lo) / 2;
+ mi = lo + (hi - lo) / 2;
} while (lo < hi);
return -lo-1;
}