提问者:小点点

从矢量<unsigned char>转换为char*包括垃圾数据


我正在尝试对一个字符串进行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];
}

vectorunsigned char字节的typedef,取自此SO答案。 base64代码也来自于这个答案(投票最多的答案,而不是接受的答案)。 运行此代码时,在VisualStudio Text Visualiser中获得以下值:

TestStringÍ

我也尝试过其他的转换方法,比如:

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

它给出了以下内容:

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

为什么我会在字符串的末尾得到垃圾数据? 我做错了什么?

编辑:阐明了我正在使用的链接问题中的哪个答案


共2个答案

匿名用户

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';

如果需要一个字符*,只需使用.c_str()

const char* cstr = decodedString.c_str();

如果需要将此传递给以char*为输入的函数,例如:

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

我们在C++中有大量的函数,抽象和容器,这些都是为了改进C语言而做出的,这样程序员就不必手写东西,而且每次编写代码时都犯同样的错误。 如果我们尽可能地使用这些功能来避免原始循环,或者像这样进行简单的修改,那将是最好的。

匿名用户

您正在编写超出所分配数组的最后一个元素的内容,这实际上会导致任何事情发生(根据C++标准)。 您需要decodedchar[decodeddata.size()]=0;