【问题标题】:How can I avoid arithmetic overflow in c++?如何避免 C++ 中的算术溢出?
【发布时间】:2020-05-14 15:57:54
【问题描述】:

这是我编译时出现警告的代码的一部分,我无法理解如何避免算术溢出问题

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).

【问题讨论】:

  • @HANA 你是说将pn 转换为std::size_t 没有解决你的问题吗? infile.seekg(static_cast<std::size_t>(pn) * sizeof(makeres));?
  • 您需要比“它不起作用”更具体。当您尝试这些解决方案时,结果如何?错误信息是相同还是不同?
  • 错误信息指向哪一行?你真的向我们展示了正确的路线吗?
  • 现在,你看到了吗? @JohnFilleau
  • 这并没有解决问题,但是使用 read 调用来爆破现有对象中的位将在除了最狭窄的情况之外的所有情况下导致麻烦。

标签: c++ function oop math overflow


【解决方案1】:

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

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

【讨论】:

    【解决方案2】:

    seekg 期望的类型是streampos,所以做如下:

    infile.seekg(static_cast<streampos>pn * sizeof(makeres));
    

    【讨论】:

    • 在编写 C++ 时为什么不使用 C++ 类型转换?
    • @HANA 它怎么不起作用?相同的错误或警告?有什么不同?
    • @BigTemp 因为我很懒。
    • @stark 够公平
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-12-06
    • 1970-01-01
    • 1970-01-01
    • 2020-03-08
    相关资源
    最近更新 更多