From 9f469e576b3e72c78a84a44b7cedcec6f03a817c Mon Sep 17 00:00:00 2001 From: Fabian Homborg Date: Mon, 4 Feb 2019 16:29:33 +0100 Subject: [PATCH] tinyexpr: Prevent possible division by zero This is possibly not actually undefined behavior because IEEE754 defines _more_ of division-by-zero, but let's be careful. Fixes #2852. --- src/tinyexpr.cpp | 8 +++++++- 1 file changed, 7 insertions(+), 1 deletion(-) diff --git a/src/tinyexpr.cpp b/src/tinyexpr.cpp index 2faf4bb9f..6cfba346d 100644 --- a/src/tinyexpr.cpp +++ b/src/tinyexpr.cpp @@ -202,7 +202,13 @@ static const te_builtin *find_builtin(const char *name, int len) { static constexpr double add(double a, double b) {return a + b;} static constexpr double sub(double a, double b) {return a - b;} static constexpr double mul(double a, double b) {return a * b;} -static constexpr double divide(double a, double b) {return a / b;} +static constexpr double divide(double a, double b) { + // If b isn't zero, divide. + // If a isn't zero, return signed INFINITY. + // Else, return NAN. + return b ? a / b : a ? copysign(1, a) * copysign(1,b) * INFINITY : NAN; +} + static constexpr double negate(double a) {return -a;} void next_token(state *s) {