]> git.tuebingen.mpg.de Git - paraslash.git/commitdiff
mood.c: Avoid integer underflow.
authorAndre Noll <maan@tuebingen.mpg.de>
Tue, 15 Mar 2016 19:48:12 +0000 (20:48 +0100)
committerAndre Noll <maan@tuebingen.mpg.de>
Tue, 15 Mar 2016 21:03:11 +0000 (22:03 +0100)
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

diff --git a/mood.c b/mood.c
index e026c960d5fd878cdca6350f3e74a40b85c338f8..415e1702a75f038694b53393d8674c426b1314c6 100644 (file)
--- 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;