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

标签 c++ compiler-errors

我在 visual studio 2019 中用 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;
}

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

上面显示的代码获取一个文件,打开它以供读取,并将内容转储到一个动态初始化的 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.

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

关于c++ - 在 C++ 代码部分,可能会写入两个字节,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57944124/

相关文章:

python - ctype在代码中没有发现属性错误

c++ - 如何在清除屏幕之前等待键盘输入(getchar 不工作)

c++ - 锁定方案黑客

c++ - 重载运算符 +

c++ - 要求约束必须评估为 bool。所以没有 SFINAE

C++:实现一个全局常量,其值由用户给出

xcode - 当我们在 swift 项目中遇到运行时错误时,为什么 Xcode 将我们发送到汇编语言的 Thread 输出?重点是什么 ?

java - 使用数组和可变长度形式参数。 (java :38: error: '.class' expected)

c++ - C++中带括号的计算器

testing - 模拟脚本语言(PHP 和 JS)的编译时检查