将unsigned char转换为字符串时,缓冲区的大小会发生变化

The size of my buffer change when I convert an unsigned char to a string

本文关键字:变化 缓冲区 char unsigned 转换 字符串      更新时间:2023-10-16

我有一个类型转换的问题,我无法解释。

这是我想做的

我有一个动态分配的缓冲区,为了使用外部库的解析函数,我需要将其转换为字符串。

实现

unsigned char* msg_data;
msg_data = (unsigned char*)malloc(msg_data_length);
string msg_data_str = std::string(reinterpret_cast<const char*>(_msg_data));
SomeObject myObject;
myObject.ParseFromString(msg_data_str);

但是事情是这样的:我的解析函数失败了,因为它接收到错误的数据大小。假设我有一个大小为msg_data_length = 10的缓冲区,我的字符串的大小为my_data_str.size() = 14

我用my_data_str.resize(my_data_length)解决了我的问题但是我想知道为什么my_data_str的大小不是直接的msg_data_length

感谢您的帮助

我假设消息数据实际上不像c风格字符串那样以零结尾,当std::string构造函数越界查找终止符时,会导致未定义的行为。

要解决这个问题,使用带两个参数的构造函数,字符串和长度。

参见std::string构造函数参考