简体   繁体   中英

in C++ code section, two bytes might be written

I am having a problem with a function, in visual studio 2019, written in c++:

#include <fstream>

//whatever...

void xorcrypt(string filename) { //the function
    ifstream inFile(filename, ios::ate);
    ifstream::pos_type size = inFile.tellg();
    char* memblock;
    memblock = new char[(unsigned int)size];
    inFile.seekg(0, ios::beg);
    inFile.read(memblock, size);
    inFile.close();
    for (long long i = 0; i < size;)
        for (int x = 0; x <= 255 && i < size; ++i, ++x)
            memblock[i] ^= x; //xor operation
    ofstream outFile;
    outFile.open(filename, ios::trunc);
    for (long long i = 0; i < size; ++i)
        outFile << memblock[i]; //The Problem
    outFile.close();
    delete[] memblock;
}

This code is Problematic, because Visual studio says that my dynamically initialized buffer, which holds the entire content of the file, might write 2 bytes to the file instead of 1... I do not know why this could e happening, and the function "XORcrypts" my files right most of the time, so I was hoping that someone Else Might Know why this is happening.

The code that is shown above takes a file, opens it to be read, and dumps the contents into a dynamically initialized char array, then the file is closed, truncated (wiped), and then the file is written to using a block of code which increments the XOR operation, per byte, to be used on the character. once this is done with the writing operation, it deletes the character array and closes the file.

I would, if possible, like to have a solution that does not create more dependency than the base c++, and fstream. Thanks in advance.

The warning occurs because the compiler can't tell what the value of size might be! It could be less than 1 (or 2), if the file is empty. Change your allocation to the following, to avoid the warning:

memblock = new char[std::max((unsigned int)size, 2u)];

(Of course, you'll need to #include <algorithm> to get std::max() .)

EDIT: For clarity, this is the warning I get without the 'fix':

warning C6385: Reading invalid data from 'memblock':  the readable size is '(unsigned int)size.public: __cdecl std::fpos<struct _Mbstatet>::operator __int64(void)const ()*1' bytes, but '2' bytes may be read.

Is this the same as you see, Eric?

Apparently, I had defined the variable like this:

   memblock = new char[(unsigned int)size];

However, there needed to be another character to hold the /0 ansi escape code, so here is the answer:

do this:

  memblock = new char[(unsigned int)size + 1];

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM