簡體   English   中英

如何避免 c++ 中的算術溢出?

[英]How can I avoid arithmetic overflow in 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).

sizeof()是一個返回std::size_t的常量表達式,這意味着理想情況下,無論您將該表達式的結果與該表達式的結果相乘,都應該是std::size_t類型。 現在,你可能會得到某種“有符號-無符號”不匹配,因為std::streamoff streamoff 是一個有符號的 integer ,這就是seekg()接受的參數,但這不應該讓你真正關心。

此外,您得到的可能不是錯誤,而是 C++ 核心指南分析警告。 假設您使用的是 Visual Studio,只需在項目屬性中將Enable Code Analysis on Build關閉即可。 無論如何,這只是一個主要的痛苦。

seekg 期望的類型是 streampos,因此請執行以下操作:

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM