簡體   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