Fix potential overflow related issues spotted by LGTM code analysis (#1402)