首页 > 解决方案 > 如何将 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));

}

标签: cmallocsizeofmemcpyconst-char

解决方案


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

推荐阅读