danial weaber
danial weaber

Reputation: 876

why binary file I/O gives some random data on reading

here Ill clearly explain what i am going to do.

I have a text file which the first 16 bytes contains a thing called a salt and the next 32 bytes contains a thing called iv. (these things are something related to encryption and its not the matter here.)

below is how the text file looks like.

now I use the below code to read them into two char arrays in order to separate them.

   ifstream infile ("salt.txt" , std::ios::binary );


   char* salt = new char[16];
   char* iv = new char[32];

   infile.read(salt , 16 );
   infile.seekg(16, ios::beg);
   infile.read(iv, 32  );

   ui->textEdit_3->append("salt : "+ QString::fromStdString(salt) );
   ui->textEdit_3->append("iv : "+ QString::fromStdString(iv) + "\n\n" );
   infile.close();

I use Qt for gui designing and the last three lines are used to display the results on a text edit.

when i read the same text file several times it gives some random data on the last 4 or 5 bytes.

the below image shows some readings took from the same text file.

enter image description here

whats the matter really going on here. I cant figure out the reason for this strange behavior.

Upvotes: 0

Views: 558

Answers (2)

Ferruccio
Ferruccio

Reputation: 100638

QString::fromStdString takes a std::string as a parameter. Since you are passing it a char *, it will be implicitly converted to a std::string using the std::string(const char*) constructor. The problem with that is that it will look for a null character as the string terminator. Which means that if the data you read contains a null character it will terminate early or (most likely what's happening here) it will go past your salt buffer until it finds a random null character in memory.

The way to fix it in either case is to force it to explicitly use the std::string(const char*, size_type) constructor: QString::fromStdString(std::string(salt, 16))

Upvotes: 5

Ed Heal
Ed Heal

Reputation: 59987

Missing the null character perhaps?

i.e. code should be

char* salt = new char[17];
char* iv = new char[33];
iv[32] = salt[16] = 0;

Upvotes: 2

Related Questions