From a37f31bbe4f1b2745ef0f617cff122a2c5f95078 Mon Sep 17 00:00:00 2001 From: Andre Noll Date: Tue, 15 Mar 2016 20:48:12 +0100 Subject: [PATCH] mood.c: Avoid integer underflow. The three variables x, s, n are all of unsigned type, and the subtraction x - s / n may underflow, resulting in a very large positive value. This should not matter since we square the difference, but on the other hand, the underflow can easily be avoided. This patch uses a temporary variable to do so. --- mood.c | 14 +++++++++----- 1 file changed, 9 insertions(+), 5 deletions(-) diff --git a/mood.c b/mood.c index e026c960..415e1702 100644 --- a/mood.c +++ b/mood.c @@ -504,7 +504,7 @@ static long compute_dynamic_score(const struct osl_row *aft_row) static int add_afs_statistics(const struct osl_row *row) { - uint64_t n, x, s; + uint64_t n, x, s, q; struct afs_info afsi; int ret; @@ -514,14 +514,18 @@ static int add_afs_statistics(const struct osl_row *row) n = statistics.num; x = afsi.last_played; s = statistics.last_played_sum; - if (n > 0) - statistics.last_played_qd += (x - s / n) * (x - s / n) * n / (n + 1); + if (n > 0) { + q = (x > s / n)? x - s / n : s / n - x; + statistics.last_played_qd += q * q * n / (n + 1); + } statistics.last_played_sum += x; x = afsi.num_played; s = statistics.num_played_sum; - if (n > 0) - statistics.num_played_qd += (x - s / n) * (x - s / n) * n / (n + 1); + if (n > 0) { + q = (x > s / n)? x - s / n : s / n - x; + statistics.num_played_qd += q * q * n / (n + 1); + } statistics.num_played_sum += x; statistics.num++; return 1; -- 2.39.5