将unsigned char转换为字符串时,缓冲区的大小会发生变化
The size of my buffer change when I convert an unsigned char to a string
我有一个类型转换的问题,我无法解释。
这是我想做的
我有一个动态分配的缓冲区,为了使用外部库的解析函数,我需要将其转换为字符串。
实现
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
构造函数参考
相关文章:
- C++字符*缓冲区的大小
- 为什么msgrcv()将垃圾字符馈送到缓冲区
- 使用动态分配的数组会导致代码分析发出虚假的C6386缓冲区溢出警告
- ostream过载时的缓冲区冲洗
- C++中的高效循环缓冲区,它将被传递给C样式数组函数参数
- C++取消引用指针.为什么会发生变化
- 为什么在读取文件大小时文件IO速度会发生变化
- Xaudio2在更改缓冲区或循环时弹出声音
- 为什么我在leetcode上收到AddressSanitizer:地址0x602000000058上的堆缓冲区溢出错误
- 如何将图像传输到c++(dll)中的缓冲区,然后在c#的缓冲区中读/写
- 如何在cpp.中使用协议缓冲区存储大缓冲区/数组(char/int)
- 多线程双缓冲区
- Android P-9.0.0_r53 Logcat主缓冲区超出定义大小
- 套接字读取后,我在缓冲区中看到意外输入
- 为什么cudaMemGetInfo报告设备内存总量的变化
- std::带有自定义缓冲区的 iostream 不允许我写入
- 从返回的顶点缓冲区查询顶点结构
- 将unsigned char转换为字符串时,缓冲区的大小会发生变化
- (DirectX 11)动态顶点/索引缓冲区实现恒定的场景内容变化
- 将内存写入文件缓冲区如何使其发生变化?