[英]C++ Program crashes when reading binary data from file of X length
我試圖從文件中讀取二進制數據,這是我的文件結構:
#define SIGNATURE_LENGTH 3
#define VERSION_LENGTH 2
#define DATACOUNT_LENGTH 4
#define COMPRESS_LENGTH 1
#define FORMAT_LENGTH 2
#define DATALENGTH_LENGTH 4
const unsigned char resSignature[SIGNATURE_LENGTH] = { 0x52, 0x45, 0x53 };
const unsigned char resVersion[VERSION_LENGTH] = { 0x01, 0x00 };
const unsigned char isCompressed[COMPRESS_LENGTH] = { 0x01 };
const unsigned char notCompressed[COMPRESS_LENGTH] = { 0x00 };
// Data Formats:
const unsigned char dataUnknown[FORMAT_LENGTH] = { 0x00, 0x00 };
const unsigned char dataXML[FORMAT_LENGTH] = { 0x01, 0x00 };
// Define header structure for resource file
struct ResHeader
{
unsigned char signature[SIGNATURE_LENGTH];
unsigned char version[VERSION_LENGTH];
};
// Define data structure for resource file
struct ResData
{
unsigned char compressed[COMPRESS_LENGTH];
unsigned char dataFormat[FORMAT_LENGTH];
unsigned char dataLength[DATALENGTH_LENGTH];
unsigned char *data;
};
我班上用的是:
std::fstream File;
// Resource file makeup
ResHeader header;
unsigned char dataCount[DATACOUNT_LENGTH];
// Vector to contain resource file data
std::vector<ResData> ResourceData;
當我嘗試從文件中讀取時程序崩潰:
int ResourceFile::LoadFile()
{
File.open("blah.dat", std::ios::in | std::ios::binary);
// Read header
File.read((char*) header.signature, SIGNATURE_LENGTH);
File.read((char*) header.version, VERSION_LENGTH);
if(!VerifyHeader())
{
File.close();
return HEADER_INCORRECT;
}
File.read((char*) dataCount, DATACOUNT_LENGTH);
long fileCount = unsignedCharArrayToLong(dataCount);
for(long i = 0; i < fileCount; ++i)
{
ResData tmp;
File.read((char*) tmp.compressed, COMPRESS_LENGTH);
File.read((char*) tmp.dataFormat, FORMAT_LENGTH);
File.read((char*) tmp.dataLength, DATALENGTH_LENGTH);
File.read((char*) tmp.data, unsignedCharArrayToLong(tmp.dataLength));
ResourceData.push_back(tmp);
}
File.close();
return SUCCESS;
}
程序崩潰了:
File.read((char*) tmp.data, unsignedCharArrayToLong(tmp.dataLength));
文件中的數據長度是282,這是讀入tmp.dataLength的內容。 所以數字是准確的。 數據也使用easy zlib進行壓縮: http : //www.firstobject.com/easy-zlib-c++-xml-compression.htm
關於我做錯了什么或者我可以做得更好的任何建議/幫助將不勝感激。 謝謝。
這個局部變量:
ResData tmp;
包含
unsigned char *data;
鑒於沒有任何代碼實際上為data
分配任何內容,它將指向內存中的某個“隨機”位置。 這意味着“未定義的行為”,並且給出了平均值和你的結果的定律,在這種情況下,“未定義的行為”意味着你的程序崩潰,這可能比替代方案更好,或者你可能會更多地抓住你的頭腦在其他地方出了問題。
你可能想要這樣的東西(在讀取dataLength
):
size_t len = unsignedCharArrayToLong(tmp.dataLength);
tmp.data = new unsigned char[len];
File.read((char*) tmp.data, len);
稍后,不要忘記取消分配數據。 或者更好的是,使用std::vector
,而不是調用new,執行data.resize(len);
並使用tmp.data.data()
獲取File.read(...)
緩沖區的地址。 這樣,你不需要記住解除分配任何東西,因為std::vector
會為你做。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.