In order to avoid overflows when calculating needed memory, cast the first variable used into a large enough type so the whole calculation is done in that type. (cherry picked from commit 838be627)