From 6843dc1272e56e91234deab486781c711436031e Mon Sep 17 00:00:00 2001 From: Olivier Gayot Date: Sun, 19 Nov 2017 11:50:16 +0100 Subject: Fixed addition with operands of different sizes When two numbers (i.e. their _operands list) had different sizes, their addition was resulting in undefined behaviour because, at some point in the computation, we were dereferencing the iterator of the shortest number (and the iterator was _operands.cend()). Fixed by virtually "padding" the shortest number with zeros. Signed-off-by: Olivier Gayot --- number.cpp | 14 +++----------- 1 file changed, 3 insertions(+), 11 deletions(-) (limited to 'number.cpp') diff --git a/number.cpp b/number.cpp index ae4b167..d16f37f 100644 --- a/number.cpp +++ b/number.cpp @@ -67,11 +67,6 @@ number::to_uint32() const number number::operator+(const number &n) const { - /* We make sure our object is greater than or equal to n. */ - if (*this < n) { - return n.operator+(*this); - } - number result; auto it = _operands.cbegin(); @@ -79,9 +74,9 @@ number::operator+(const number &n) const bool carry = false; - while (it != _operands.cend()) { - const auto n1 = *it; - const auto n2 = *it_n; + while (it != _operands.cend() || it_n != n._operands.cend()) { + const auto n1 = (it != _operands.cend()) ? *it++ : 0; + const auto n2 = (it_n != n._operands.cend()) ? *it_n++ : 0; result._operands.push_back(n1 + n2 + (carry ? 1 : 0)); @@ -90,9 +85,6 @@ number::operator+(const number &n) const } else { carry = ((UINT32_MAX - n1 - (carry ? 1 : 0)) < n2); } - - ++it; - ++it_n; } if (carry) { -- cgit v1.2.3