簡體   English   中英

從向量轉換<unsigned char> to char* 包含垃圾數據</unsigned>

[英]Convert from vector<unsigned char> to char* includes garbage data

我正在嘗試 base64 解碼一個字符串,然后將該值轉換為 char 數組以供以后使用。 解碼工作正常,但是在轉換時我得到了垃圾數據。

這是我到目前為止的代碼:

std::string encodedData = "VGVzdFN0cmluZw=="; //"TestString"
std::vector<BYTE> decodedData = base64_decode(encodedData);

char* decodedChar;
decodedChar = new char[decodedData.size() +1]; // +1 for the final 0
decodedChar[decodedData.size() + 1] = 0; // terminate the string
for (size_t i = 0; i < decodedData.size(); ++i) {
    decodedChar[i] = decodedData[i];
}

vector<BYTE>unsigned char BYTE 的typedef ,取自SO 答案。 base64 代碼也來自這個答案(最受好評的答案,而不是接受的答案)。 當我運行此代碼時,我在 VisualStudio Text Visualiser 中獲得以下值:

TestStringÍ

我還嘗試了其他轉換方法,例如:

char* decodedChar = reinterpret_cast< char *>(&decodedData[0]);

這給出了以下內容:

TestStringÍÍÍýýýýÝÝÝÝÝÝÝ*b4d“

為什么我在字符串末尾得到垃圾數據? 我究竟做錯了什么?

編輯:澄清了我正在使用的鏈接問題中的哪個答案

char* decodedChar;
decodedChar = new char[decodedData.size() +1]; // +1 for the final 0

當您有可用的std::string為您執行此操作時,為什么要手動分配一個緩沖區然后復制到它?

做就是了:

std::string encodedData = "VGVzdFN0cmluZw=="; //"TestString"
std::vector<BYTE> decodedData = base64_decode(encodedData);

std::string decodedString { decodedData.begin(), decodedData.end() };

std::cout << decodedString << '\n';

如果您需要一個char * ,只需使用.c_str()

const char* cstr = decodedString.c_str();

如果您需要將此傳遞給以char*作為輸入的 function,例如:

void someFunc(char* data);
//...
//call site
someFunc( &decodedString[0] );

我們在 C++ 中有大量的函數、抽象和容器,它們是為了改進 C 語言而設計的,這樣程序員就不必在每次編碼時手動編寫東西並犯同樣的錯誤。 如果我們盡可能使用這些功能來避免原始循環或進行類似這樣的簡單修改,那將是最好的。

您正在寫入超出分配數組的最后一個元素,這可能會導致任何事情發生(根據 C++ 標准)。 你需要decodedChar[decodedData.size()] = 0;

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM