summaryrefslogtreecommitdiff
path: root/sha1-lookup.c
diff options
context:
space:
mode:
authorDerrick Stolee <dstolee@microsoft.com>2017-10-08 18:29:37 (GMT)
committerJunio C Hamano <gitster@pobox.com>2017-10-09 23:57:24 (GMT)
commit19716b21a4255ecc7148b54ab2c78039c59f25bf (patch)
tree5f1cecbffc543c64e7c4c4f371d204424e1ce1bb /sha1-lookup.c
parent217f2767cbcb562872437eed4dec62e00846d90c (diff)
downloadgit-19716b21a4255ecc7148b54ab2c78039c59f25bf.zip
git-19716b21a4255ecc7148b54ab2c78039c59f25bf.tar.gz
git-19716b21a4255ecc7148b54ab2c78039c59f25bf.tar.bz2
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 2552b79..4cf3ebd 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;
}