diff options
author | Olivier Gayot <og@satcom1.com> | 2017-11-19 11:50:16 +0100 |
---|---|---|
committer | Olivier Gayot <og@satcom1.com> | 2017-11-19 16:15:32 +0100 |
commit | 6843dc1272e56e91234deab486781c711436031e (patch) | |
tree | 25c5daa396966b635a6025ea6a607ce46adba2d7 /number.cpp | |
parent | 615b8a00aedb3363b4749f706d6df51846b743ac (diff) |
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 <og@satcom1.com>
Diffstat (limited to 'number.cpp')
-rw-r--r-- | number.cpp | 14 |
1 files changed, 3 insertions, 11 deletions
@@ -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) { |