我一次从文件中读取大量二进制数据时遇到问题。以字节方式读取相同数量的字节是有效的。我必须遵循示例代码:
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);
如果我运行此代码,它会因Segmentation故障而崩溃。相应的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.
我希望这些信息足以让有人帮忙。
提前致谢
答案 0 :(得分:1)
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);