Reputation: 61515
I am trying to write a program that reads in binary files using C++. I am running into some unusual output that I was hoping for some help with.
I have a binary file that starts with these 4 bytes:
A1 B2 C3 D4 (verified using hexdump -C
)
And here is the code I am using to read these 4 bytes in:
#include <iostream> // for reading and writing files
#include <fstream>
using namespace std;
char * buffer;
unsigned int LENGTH = 4;
int main(int argc, char ** argv)
{
// open the binary file
ifstream infile ("dump", ios::binary | ios::in);
// create a buffer
buffer = new char[LENGTH];
// read LENGTH bytes from the file
infile.read(buffer, LENGTH);
// append the null byte to terminate the string
buffer[LENGTH] = '\0';
// loop over the 4 bytes read, and print
for(int i = 0; i < LENGTH; i++)
{
printf("Buffer[%d] is %X\n", i, buffer[i]);
}
delete[] buffer;
infile.close();
return 0;
}
This program gives me these actual results:
Buffer[0] is FFFFFFA1
Buffer[1] is FFFFFFB2
Buffer[2] is FFFFFFC3
Buffer[3] is FFFFFFD4
BUT, I would expect these results:
Buffer[0] is A1
Buffer[1] is B2
Buffer[2] is C3
Buffer[3] is D4
Can anyone explain to me where the 3 0xFF bytes are coming from ? It only seems to be affecting the first 4 bytes of the file, the next 4 bytes print out as expected without any 0xFF bytes prepended.
Upvotes: 1
Views: 2833
Reputation: 476910
The char
buffer[i]
is default promoted when passed as a variable argument. To get the right value, say static_cast<unsigned char>(buffer[i])
.
Moreover, buffer[LENGTH]
is out of bounds and thus undefined behaviour.
Upvotes: 8
Reputation: 399703
You can't read LENGTH
bytes of content, and terminate at offset LENGTH
in a buffer of size LENGTH
. This is an off-by-one error.
buffer = new char[LENGTH];
This gives you space for LENGTH
characters, with indices 0 through LENGTH - 1
. So this:
buffer[LENGTH] = '\0';
writes outside the allocated memory, invoking undefined behavior.
Upvotes: 5