c - 如何将 const unsigned char* payLoad 转换为 char* 并复制它?
问题描述
我正在尝试将 a 转换const unsigned char*
为char*
并制作副本。我尝试了以下代码的几种变体,但通常会出现内存异常。此函数驻留在用 C 编写的应用程序中。
下面的函数是我想要创建的
//global variable
char* copiedValue;
void convertUnsignedChar(const unsigned char* message){
copiedValue = malloc(sizeof(message));
(void)memcpy(copiedValue, message, sizeof(message));
}
解决方案
malloc(sizeof(message))
only allocates space for a char *
pointer, probably 8 bytes. You need to allocate space for the data which message
points to.
There's a bit of a problem: how much data is pointed at by message
? Is it null terminated? Let's assume it is, then you can use strlen
. Don't forget space for the null byte!
copiedValue = malloc(strlen((char*)message) + 1);
Similarly for memcpy
.
memcpy(copiedValue, message, strlen((char*)message) + 1);
Note, there's no need to cast memcpy
's return value to void
.
Or use the POSIX strdup
function.
copiedValue = strdup((char *)message);
推荐阅读
- reporting-services - CloudFlare 源证书在 SSRS 上配置
- reactjs - React App 在构建中没有媒体文件
- android - Jetpack Compose 中约束布局的权重
- python - 如何从 tif 使用 python netCDF4 创建 netCDF 文件?
- python - 使用 pandas 平衡数据集
- python - 模型中的 Django 3 动态默认值
- python - 带有 .toml 配置和预提交钩子的 Flakehell
- list - 我应该如何删除列表中的非数字使用序言
- python - 为 Djoser 中未激活的用户返回适当的错误
- ruby-on-rails - 如何使用表单在 Ruby on Rails 中设置参数值(对于 Scope)?