首页 > 解决方案 > 如何避免 C++ 中的算术溢出?

问题描述

这是我编译时有警告的代码的一部分,我不明白如何避免算术溢出问题

void read(int pn) //read person number pn
{
    ifstream infile;
    infile.open("data.txt", ios::binary);
    infile.seekg(pn * sizeof(makers)); // this is the line I get warning
    infile.read((char*)this, sizeof(*this));
}

我得到的警告:

Arithmetic overflow: Using operator '*' on a 4 byte value and then
casting the result to a 8 byte value. Cast the value to the wider
type before calling operator '*' to avoid overflow (io.2).

标签: c++functionoopmathoverflow

解决方案


sizeof()是一个返回的常量表达式std::size_t,这意味着理想情况下,无论您将该表达式的结果乘以什么,都应该是 type std::size_t。现在,无论如何你可能会得到某种“有符号-无符号”不匹配,因为std::streamoff它是一个有符号整数,这就是seekg()作为参数接受的,但这不应该让你真正关心。

此外,您得到的可能不是错误,而是 C++ Core Guidelines 分析警告。假设您使用的是 Visual Studio,只需Enable Code Analysis on Build在项目属性中关闭即可。无论如何,这只是一个主要的痛苦。


推荐阅读