From 8f69e217bf08bbdf5a4a84b4d2934905c8dafd9a Mon Sep 17 00:00:00 2001 From: Walter Bright Date: Fri, 5 Aug 2016 00:39:33 -0700 Subject: [PATCH] comparison.d: add overflow checks --- std/algorithm/comparison.d | 10 ++++++++-- 1 file changed, 8 insertions(+), 2 deletions(-) diff --git a/std/algorithm/comparison.d b/std/algorithm/comparison.d index bb943d00a42..bd9be5c5c44 100644 --- a/std/algorithm/comparison.d +++ b/std/algorithm/comparison.d @@ -1001,13 +1001,19 @@ private: ref CostType matrix(size_t row, size_t col) { return _matrix[row * cols + col]; } void AllocMatrix(size_t r, size_t c) @trusted { + import core.checkedint : mulu; + bool overflow; + const rc = mulu(r, c, overflow); + if (overflow) assert(0); rows = r; cols = c; - if (_matrix.length < r * c) + if (_matrix.length < rc) { import core.stdc.stdlib : realloc; import core.exception : onOutOfMemoryError; - auto m = cast(CostType *)realloc(_matrix.ptr, r * c * _matrix[0].sizeof); + const nbytes = mulu(rc, _matrix[0].sizeof, overflow); + if (overflow) assert(0); + auto m = cast(CostType *)realloc(_matrix.ptr, nbytes); if (!m) onOutOfMemoryError(); _matrix = m[0 .. r * c];