【问题标题】:std::ifstream read reading wrong size for large numbersstd::ifstream 读取大数的错误大小
【发布时间】:2015-06-05 22:32:32
【问题描述】:

我在一次从文件中读取一大块二进制数据时遇到问题。按字节读取相同数量的字节是有效的。我必须遵循示例代码:

std::ifstream inFile;
inFile.open("example.bin", std::ios::binary | std::ios::in);
uint32_t bytesToAllocate = static_cast<uint32_t>(this->sectionLength)-4;
this->binaryData = new uint8_t[bytesToAllocate];
inFile.read(reinterpret_cast<char*>(&this->binaryData), bytesToAllocate);

如果我运行此代码,它会因分段错误而崩溃。对应的valgrind输出为:

==13336== Invalid write of size 2
==13336==    at 0x4C3090B: memcpy@@GLIBC_2.14 (in /usr/lib/valgrind/vgpreload_memcheck-amd64-linux.so)
==13336==    by 0x4EDB1F2: std::basic_streambuf<char, std::char_traits<char> >::xsgetn(char*, long) (in /usr/lib/x86_64-linux-gnu/libstdc++.so.6.0.20)
==13336==    by 0x4EF486D: std::basic_filebuf<char, std::char_traits<char> >::xsgetn(char*, long) (in /usr/lib/x86_64-linux-gnu/libstdc++.so.6.0.20)
==13336==    by 0x4EB877A: std::istream::read(char*, long) (in /usr/lib/x86_64-linux-gnu/libstdc++.so.6.0.20)
==13336==    by 0x4038F4: Reader::readFile(std::string) (reader.cpp:145)
==13336==    by 0x401698: main (main.cpp:16)
==13336==  Address 0xfff001000 is not stack'd, malloc'd or (recently) free'd

但是当我使用以下代码逐字节读取相同数量的日期时

for(int i=0; i< bytesToAllocate; ++i)
    inFile.read(reinterpret_cast<char*>(&this->binaryData[i]), 1);

程序运行并且 valgrind 没有抱怨。在我的例子中,bytesToAllocate 是 5370。

我希望这些信息足以帮助某人。

提前致谢

【问题讨论】:

    标签: c++ segmentation-fault valgrind ifstream


    【解决方案1】:
    this->binaryData = new uint8_t[bytesToAllocate];
    inFile.read(reinterpret_cast<char*>(&this->binaryData), bytesToAllocate);
    

    您正在读取this-&gt;binaryData 的地址。但是this-&gt;binaryData就是你想要的地址。你想要:

    this->binaryData = new uint8_t[bytesToAllocate];
    inFile.read(reinterpret_cast<char*>(this->binaryData), bytesToAllocate);
    

    【讨论】:

    • 啊,愚蠢的错误,你当然是对的。感谢您的快速答复。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-03-13
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多