繁体   English   中英

在 C++ 代码部分,可能会写入两个字节

[英]in C++ code section, two bytes might be written

我在用 C++ 编写的 Visual Studio 2019 中遇到了一个函数问题:

#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;
}

这段代码是有问题的,因为 Visual Studio 说我的动态初始化缓冲区,它保存了文件的全部内容,可能会向文件写入 2 个字节而不是 1 个......我不知道为什么会发生这种情况,函数大多数时候“异或加密”我的文件是正确的,所以我希望其他人可能知道为什么会发生这种情况。

上面显示的代码获取一个文件,打开它以供读取,并将内容转储到动态初始化的 char 数组中,然后关闭文件,截断(擦除)文件,然后使用代码块写入文件这会增加要在字符上使用的每个字节的 XOR 操作。 写入操作完成后,它会删除字符数组并关闭文件。

如果可能的话,我希望有一个解决方案不会比基本的 c++ 和 fstream 产生更多的依赖。 提前致谢。

出现警告是因为编译器无法判断size的值可能是什么! 如果文件为空,它可能小于 1(或 2)。 将您的分配更改为以下内容,以避免出现警告:

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

(当然,您需要#include <algorithm>来获得std::max() 。)

编辑:为清楚起见,这是我在没有“修复”的情况下收到的警告:

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.

这和你看到的一样吗,埃里克?

显然,我已经定义了这样的变量:

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

但是,需要有另一个字符来保存 /0 ansi 转义码,所以这里是答案:

做这个:

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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