std::ifstream read 读取大数字的大小错误

std::ifstream read reading wrong size for large numbers

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

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

程序 运行s 和 valgrind 没有报错。在我的例子中 bytesToAllocate 是 5370。

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

提前致谢

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

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

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