0

I'm writing a simple console application in Visual Studio C++. I want to read a binary file with .cer extension to a byte array.

ifstream inFile;
size_t size = 0; 
char* oData = 0;
inFile.open(path, ios::in|ios::binary);

if (inFile.is_open())
{
    size = inFile.tellg();     // get the length of the file
    oData = new char[size+1];  //  for the '\0'
    inFile.read( oData, size );
    oData[size] = '\0' ;       // set '\0'

    inFile.close();
    buff.CryptoContext = (byte*)oData;
    delete[] oData;
}

But when I launch it, I receive in all the oData characters the same char, every time another one, For example:

oData = "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@...".

Then I tried another way:

std::ifstream in(path, std::ios::in | std::ios::binary);

if (in)
{
    std::string contents;

    in.seekg(0, std::ios::end);
    contents.resize(in.tellg());

    in.seekg(0, std::ios::beg);
    in.read(&contents[0], contents.size());

    in.close();
}

Now the content has very strange values: a part of the values is correct, and a part is negative and strange values (maybe it is related to signed char and unsigned char?).

Does anyone have any idea?

Thanks ahead!

Carsten
  • 11,287
  • 7
  • 39
  • 62
user1835297
  • 1,059
  • 2
  • 12
  • 24
  • The line `in.read( &contents[0], contents.size() )` is *probably* undefined behaviour, and *definitely* a very bad idea. – DevSolar Mar 20 '13 at 12:04

2 Answers2

1

You are setting CryptoContext to point to your data by byte pointer, and after that you delete that data!

buff.CryptoContext = (byte*)oData;
delete[] oData;

After this lines CryptoContext is pointing to released and invalid data. Just keep oData array longer in memory and delete it after you are done with decoding or whatever you are doing with it.

yattering
  • 436
  • 4
  • 7
1

Looking at the first version:

What makes you think that tellg gets the size of the stream? It does not, it returns the current read position. You then go on to give a pointer to your data to buff.CryptoContents and promptly delete the data pointed to! This is very dangerous practice; you need to copy the data, use a smart pointer or otherwise ensure the data has the correct lifespan. It is likely the deletion is stomping your data with a marker to show it has been deleted if you're running in debug mode which is why you are getting the stream of identical characters.

I suspect your suggestion about signed and unsigned may be correct for the second but I can't say without seeing your file and data.

Jack Aidley
  • 19,439
  • 7
  • 43
  • 70